Update a numeric property of a JSON object in an array


Update a numeric property of a JSON object in an array



My JSON config.json:


[
{
"names":"Steam",
"count": 1,
},
{
"names":"game",
"count": 2,
}
]



I need to update count's property in the array in c#.
I tried


count


JObject objectproperty = JObject.Parse(File.ReadAllText(@"config.json"));



but this gives me the error


Newtonsoft.Json.JsonReaderException: "Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1."





That's not a valid json object
– Mardoxx
Jun 30 at 23:42





The exception message tells you the solution. Use JArray for arrays, not JObject (which is, obviously, for objects)
– Camilo Terevinto
Jun 30 at 23:56


JArray


JObject





I misstiped Mardoxx. Anyways this wasn't my problem in the first place
– oSumAtrIX
Jul 1 at 11:31




1 Answer
1



You can use a JToken
Assuming that your JSON is:
(notice I had to remove some ,)


,


[
{
"names":"Steam",
"count": 1
},
{
"names":"game",
"count": 2
}
]



You can use this:


var config_file = @"config.json";

var objectproperty = JToken.Parse(File.ReadAllText(config_file));
foreach (var obj in objectproperty)
{
var count = (long)obj["count"];

obj["count"] = count * 3;
}

System.IO.File.WriteAllText(config_file, objectproperty.ToString());






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

PySpark - SparkContext: Error initializing SparkContext File does not exist

List of Kim Possible characters

Python Tkinter Error, “Too Early to Create Image”