Home > Back-end >  How to add property in existing json
How to add property in existing json

Time:08-11

I receive a JSON file like this:

{
    "Name": "testeName",
    "type": "unique",
    "TestData": [{
        "price": 2.3
    }]
}

I want to add a new property ("type":"unique") to each object in TestData to be like this in the end:

{
    "Name": "testeName",
    "type": "unique",
    "TestData": [{
        "price": 2.3,
        "type": "unique"
    }]
}

Is there any way to do it with less code? I try this but there's a lot of code, I believe there must be a simpler way:

using (MemoryStream memoryStream1 = new MemoryStream())
{
    using (Utf8JsonWriter utf8JsonWriter1 = new Utf8JsonWriter(memoryStream1))
    {
        using (JsonDocument jsonDocument = JsonDocument.ParseValue(ref reader))
        {
            utf8JsonWriter1.WriteStartObject();

            foreach (var element in jsonDocument.RootElement.EnumerateObject())
            {
                if (element.Name == "price")
                {
                    // Copying existing values from "TestData" object
                    foreach (var testDataElement in element.Value.EnumerateArray())
                    {
                        utf8JsonWriter1.WritePropertyName(element.Name);

                        // Staring new object
                        utf8JsonWriter1.WriteStartObject();

                        // Adding "Name" property
                        utf8JsonWriter1.WritePropertyName("type");
                        utf8JsonWriter1.WriteStringValue("unique");

//System.InvalidOperationException : 'Cannot write the start of an object or array without a property name. Current token type is 'String'.'
                        testDataElement.WriteTo(utf8JsonWriter1); 
                    }

                    utf8JsonWriter1.WriteEndObject();
                }
                else
                {
                    element.WriteTo(utf8JsonWriter1);
                }
            }

            utf8JsonWriter1.WriteEndObject();
        }
    }

    var resultJson = Encoding.UTF8.GetString(memoryStream1.ToArray());
}

CodePudding user response:

you can try this code

    using Newtonsoft.Json;

    var jsonObject = JObject.Parse(json);
    var testDataObj =  (JObject) ((JArray)jsonObject["TestData"])[0];
    
    testDataObj.Add("type", "unique");
    json=jsonObject.ToString();

result

{
  "Name": "testeName",
  "type": "unique",
  "TestData": [
    {
      "price": 2.3,
      "type": "unique"
    }
  ]
}

CodePudding user response:

Can you use the Newtonsoft JSON Nuget package?

You can read JSON from a file, then use the JObject.Add method to add a property and value to the JSON object:

using (StreamReader file = File.OpenText("[insert your file path here]"))
using (JsonTextReader jtReader = new JsonTextReader(file))
{
    JObject jObj = (JObject)JToken.ReadFrom(reader);
    jObj.Add("type", "unique");
}

CodePudding user response:

In .NET 6 and later you may use the new JsonNode editable JSON Document Object Model to load, modify and re-serialize your JSON:

// Load the file
JsonObject root;
using (var stream = File.OpenRead(inputFileName))
{
    root = (JsonNode.Parse(GetJson()) ?? new JsonObject()).AsObject();
}

// Add "type" to "TestData[*]"
if (root["TestData"] is JsonArray array)
{
    foreach (var obj in array.OfType<JsonObject>())
    {
        obj["type"] = "unique";
    }
}

//Examine the resulting JSON string
var resultJson = root.ToString();

//Or write back the file directly, without using an intermediate JSON string
using (var stream = File.Create(outputFileName))
using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }))
{
    root.WriteTo(writer);
}

Demo fiddle here.

  • Related