-1

Here is my json Array, i want to add a new field in array but i dont know how to loop it

{
    "data": {
        "pasca": [
            {
                "code": "PDI1231",
                "name": "Water Bottle",
                "status": 1,
                "price": 2500,
                "type": "plastic"
            },
            {
                "code": "PDI9999",
                "name": "Soccel Ball",
                "status": 1,
                "price": 99123,
                "type": "plastic"
            }
        ]
    }
}

i want to add a new field in pasca array like this

"pasca": [
            {
                "code": "PDI1231",
                "name": "Water Bottle",
                "status": 1,
                "price": 2500,
                "type": "plastic",
                "new_field_1": "new value_1",
                "new_field_2": "new value_2"
            }
        ]
3
  • What have you tried, what library do you use? Commented Jul 28, 2020 at 7:48
  • 1
    1) Deserialize the JSON (even into a JSON.NET JObject, for example), 2) Add the new array items. 3) Serialize the JSON. Commented Jul 28, 2020 at 7:49
  • 1
    Does this answer your question? Add a field into JSON array Commented Jul 28, 2020 at 7:53

1 Answer 1

1

If you are using Newtosoft's Json.NET it can be done as simple as that:

var jObj = JsonConvert.DeserializeObject<JObject>(json);
foreach(var el in jObj["data"]["pasca"])
{
    el["new_field_1"] = "new value_1";
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much, where do you get that documentation for looping like that ?
@MAndreJuliansyah Was glad to help! Newtonsoft has pretty extensive documentation.

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.