1

I have a complex json file where I can have multiple type of resources, type could be repeating as well. Given this I have two questions, I tried to search on net but didn't find any clue.

  1. How I can find specific type say type3 resource object, it could return multiple results

  2. Once I find specific resource, I want to add one more property and save it back as json

    { 
    "resources": [{
        "type": "type1",
        "name": "dummy1",
        "properties": {
            "p1": "v1"
        }
    }, {
        "type": "type2",
        "name": "dummy2",
        "properties": {
            "p1": "v1",
            "p2": {
                "k1": "v1"
            }
        }
    }, {
        "type": "type3",
        "name": "dummy3",
        "properties": {
            "p1": {
                "k1": "v1"
            },
            "p2": {
                "k1": "v1",
                "k2": "v2"
            }
        }
    }, {
        "type": "type3",
        "name": "dummy4",
        "properties": {
            "p1": {
                "k1": "v1"
            },
            "p2": {
                "k1": "v1",
                "k2": "v2"
            }
        }
        }]
    }
    

1 Answer 1

2

First off, get a JSON library. I recommend Newtonsoft.Json (install as a NuGet package).

I'm using a File api, but it's pretty easy to construct a JObject in another way. The ToString call returns the JSON string again. I'm also using Linq to find the array elements where the type is type3.

JObject jObject = JObject.Load(
    new JsonTextReader(File.OpenText("Data.json")));
JArray resources = (JArray)jObject["resources"];
foreach (var type3Resource in resources
    .Where(obj => obj["type"].Value<string>() == "type3"))
{
    type3Resource["SpecialValue"] = 3;
}

File.WriteAllText("Data2.json", 
    jObject.ToString(Formatting.Indented));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.