Search code examples
c#string-interpolation

C# string interpolation-escaping double quotes and curly braces


guys,

I'm building a JSON object from an interpolated string, and not getting how escaping works. I have to use double quotes for the API.

This does not interpolate the expressions between the curly braces:

@"{{
                        ""name"":""{taskName}"", 
                        ""products"": [    
                                    {""product"": ""ndvi_image"", ""actions"": [""mapbox"", ""processed""]}, 
                                    {""product"": ""true_color"", ""actions"": [""mapbox"", ""processed""]}
                                  ], 
                        ""recurring"":true,
                        ""query"":    {
                                        ""date_from"": ""{dateFromString}"",
                                        ""date_to"": ""{dateToString}"",
                                        ""aoi"": {polygon}
                                    },
                        ""aoi_coverage_percentage"":90
                        }}";

This throws a bunch of errors-apparently, the curly brackets are not being escaped properly:

$"{{
                        ""name"":""{taskName}"", 
                        ""products"": [    
                                    {""product"": ""ndvi_image"", ""actions"": [""mapbox"", ""processed""]}, 
                                    {""product"": ""true_color"", ""actions"": [""mapbox"", ""processed""]}
                                  ], 
                        ""recurring"":true,
                        ""query"":    {
                                        ""date_from"": ""{dateFromString}"",
                                        ""date_to"": ""{dateToString}"",
                                        ""aoi"": {polygon}
                                    },
                        ""aoi_coverage_percentage"":90
                        }}";

How should I format it in order to preserve the internal double quotes and outer brackets while allowing for the values inside the single brackets to be interpolated?


Solution

  • It seems that you have missed escape for the products and query objects:

    $@"{{
        ""name"":""{taskName}"",
        ""products"": [
            {{""product"": ""ndvi_image"", ""actions"": [""mapbox"", ""processed""]}},
            {{""product"": ""true_color"", ""actions"": [""mapbox"", ""processed""]}}
        ],
        ""recurring"":true,
        ""query"": {{
            ""date_from"": ""{dateFromString}"",
            ""date_to"": ""{dateToString}"",
            ""aoi"": {polygon}
        }},
        ""aoi_coverage_percentage"":90
    }}";