JObject parse returns extra curly braces

Viewed 1661

I have a variable projectData that contains a valid json string that is stored in a database.

After doing the following:

JObject obj = new JObject();
obj = JObject.Parse(projectData);

Instead of getting

{
"devices": {
    "device_A": {
        "id": "12345",
        "name": "test",
        "enabled": true
    }
  }
}

I get this instead:

    {{
        "devices": {
            "device_A": {
                "id": "12345",
                "name": "test",
                "enabled": true
            }
        }
    }}

So basically an aditional { and } were added to my json string.

I have also tried the following:

obj = JsonConvert.DeserializeObject<JObject>(projectData);

and it didnt work.

Why is this a problem to me?

I want to iterate over the obj["devices"] array, and when I do the following

foreach(var d in obj["devices"])

It simply doesnt work because of the double curly braces.

Is there a solution to my problem?

Thank you

1 Answers
{
"devices": {
    "device_A": {
        "id": "12345",
        "name": "test",
        "enabled": true
    }
  }
}

Your json shows devices as a json object and not an array. You cannot iterate over it with a for loop.

You can access the data by parsing it first and then accessing the properties by using the [] brackets.

var obj = JObject.Parse(jsonString);
Console.WriteLine(obj["devices"]["device_A"]["id"].Value<string>());

//prints
12345

// To Loop through multiple devices... you can use this.
foreach (var device in ((JObject)obj["devices"]).Properties())
    Console.WriteLine(obj["devices"][device.Name]["id"]);

Also, when you are using the debug mode, the watch or locals will show {{ }} because the braces are escaped.


Array version of Json

If your json looked like below, then you can use the for loop to access the elements of the JArray.

{
"devices": [
    {
      "device_A": {
        "id": "12345",
        "name": "test",
        "enabled": true
      }
    }
  ]
}

with the above json, you can use the for loop in the following way,

var obj = JObject.Parse(json);
foreach (var device in obj["devices"])
    Console.WriteLine(device["device_A"]["id"]);

// Prints
12345
Related