1

I need to add some more data into existing JSON

eg:

{
    "OrderId":"abc",
    "products":["a","b","c","etc"]
}

how to add more into products

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Roadside Romeozz
  • 73
  • 1
  • 1
  • 8
  • There is no such thing as a JSON Array. JSON is a text format, like CSV or XML. – Heretic Monkey Jun 03 '20 at 11:59
  • As such, how do you have this JSON right now? As a string? As an object? – Heretic Monkey Jun 03 '20 at 12:01
  • 1
    @HereticMonkey Your linked answer is about javascript, not c#. Also, despite being text format json has concept of array elements. – Guru Stron Jun 03 '20 at 12:07
  • @GuruStron JSON has a format for serializing arrays, but it does not have arrays. – Heretic Monkey Jun 03 '20 at 12:09
  • 1
    The proper duplicate is [json add new object to existing json file C#](https://stackoverflow.com/q/33081102/215552) – Heretic Monkey Jun 03 '20 at 12:11
  • 1
    @HereticMonkey 1) this is also not a proper duplicate 2) if you don't agree with wording you can dicuss it with [w3schools](https://www.w3schools.com/js/js_json_arrays.asp) or [ietf rfc](https://tools.ietf.org/rfc/rfc7159.txt) having next wording: "This is a JSON array containing two objects:" – Guru Stron Jun 03 '20 at 12:14
  • @GuruStron "this is also not a proper duplicate" is not swaying me with well-reasoned arguments. If you don't feel it answers the question, edit the question to make it clear why it is not (as described in the [help center](https://stackoverflow.com/help/duplicates)). W3Schools is not what I would consider a trustworthy source of anything. I may bring it up with the IETF. – Heretic Monkey Jun 03 '20 at 12:22
  • @HereticMonkey it does not answer the question because it is about adding an object to existing json (which OP knows how to do, see link in my answer) and not a new element to an array in existing json, and there is a difference in handling those in c#, not a big one though. – Guru Stron Jun 03 '20 at 12:28

2 Answers2

0

The approach would be similar to used in answer to your previous question, but you will need to convert element to JArray:

var x = @"{
    'OrderId':'abc',
    'products':['a','b','c','etc']
}";

var jObj = JObject.Parse(x);
((JArray)jObj["products"]).Add("new");
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
-1

Try this:

var jObject = JObject.Parse(json); 
var jArray = jObject["products"] as JArray; 
jArray?.Add("new_product");
Tomas Chabada
  • 2,869
  • 1
  • 17
  • 18