1

using c# - I have a string of valid json, and am attempting to parse it into a Dictionary but am struggling with the syntax to do so.

Here's an example of the data I'd like to parse:

{
  "data": {
    "KeyOne": {
      "val": "first!"
      "fooBar": "invalid data not needed",
    },
    "anotherKey": {
      "val": null
    },
    "TheThirdKey": {
      "val": 999
      "fooFooBarBar": "more unneeded data",
    },
    "KeyKeyKey": {
      "val": "super neato something"
    },
    ...

this needs to be moved into a Dictionary<string, object> with some fairly specific rules:

  1. the ever changing element name is the key ('KeyOne', 'anotherKey'...) - this is unique within the dataset
  2. for the dictionary value, I ONLY need the string or number or null that is the value of 'val' ('first', null, 999, ...)

so my final dictionary should be something like:

"KeyOne"     : "first!"
"anotherKey" : null
"TheThirdKey": 999
"KeyKeyKey"  : "super neato something"

I've tried to parse this using different variations of

JsonConvert.DeserializeObject<Dictionary<string, object>

I've also tried iterating over the jTokens as such:

JObject jObject = JObject.Parse(jsonString);
List<JToken> jTokens = jObject["data"].Children().ToList();
foreach (JToken jToken in jTokens) { ...

but after so many hours of trying, I am getting embarrassingly nowhere... Hopefully this is something that can be performed with Json.NET, but I have yet to figure it out.

Thoughts?

0

1 Answer 1

2

You could do it this way:

JObject jObject = JObject.Parse(jsonString);
var dataChildren = jObject["data"].Children().Cast<JProperty>();
Dictionary<string, object> result = dataChildren
       .ToDictionary(x => x.Name, x => x.Value["val"].Value<JValue>().Value);

You will get a Dictionary<string,object> as a result

Sign up to request clarification or add additional context in comments.

1 Comment

thank you! this works exactly as expected, and is super clean code :)

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.