Home > Mobile >  Reformatting a JSON in C#
Reformatting a JSON in C#

Time:11-09

I have a JSON response here,

{
  "Items": [
    {
      "Key": {
        "timestamp": "2022-11-06T20",
        "value": 100.80
      }
    },
    {
      "Key": {
        "timestamp": "2022-11-07T08",
        "value": 100.90
      }
    }
  ]
}

That I would like to reformat to this:

{
  "Key": [
    {
      "timestamp": "2019-01-08T20",
      "value": 12.44
    },
    {
      "timestamp": "2018-12-12 16:23:00",
      "value": 12.45
    }
  ]
}

For all responses, the Key must only be on the top once followed by an array of timestamps and values, and remove the Items parent value completely. I have tried doing this and messing around with the implementation, but I keep receiving multiple different errors. Is this the correct idea to do it or is there a better way to implement this?

        JObject obj = JObject.Parse(jsonOutput);
        JObject newObj = new JObject();
        new JProperty("KEY", new JArray(
            .Children<JProperty>()
            .Select(j => new JObject(


                    new JProperty("timestamp", j.Value["timestamp"]),
                    new JProperty("value", j.Value["value"])
                    )
                )
           )
       );
       jsonOutput = newObj.ToString();

What is the correct way to implement this idea? Thanks!

CodePudding user response:

you can fixed it in one line

jsonOutput = new JObject {new JProperty("Key", ((JArray)JObject.Parse(jsonOutput)
["Items"]).Select(s => s["Key"]))}.ToString();

CodePudding user response:

This can be done very easily by combining

  1. SelectTokens() with a JSONPath wildcard operator for the Items[*] array to select all required JSON objects.

  2. Serialization of an anonymous type object to create the required output structure.

Thus:

var query = obj.SelectTokens("Items[*].Key");
jsonOutput = JsonConvert.SerializeObject(new { Key = query }, Formatting.Indented);

Demo fiddle here.

  • Related