Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a JSON object in C# when I don't know the key in advance?

Tags:

json

c#

json.net

I have some JSON data that looks like this:

{
  "910719": {
    "id": 910719,
    "type": "asdf",
    "ref_id": 7568
  },
  "910721": {
    "id": 910721,
    "type": "asdf",
    "ref_id": 7568
  },
  "910723": {
    "id": 910723,
    "type": "asdf",
    "ref_id": 7568
  }
}

How can I parse this using JSON.net? I can first do this:

JObject jFoo = JObject.Parse(data);

I need to be able to iterate over each object in this list. I would like to be able to do something like this:

foreach (string ref_id in (string)jFoo["ref_id"]) {...}

or

foreach (JToken t in jFoo.Descendants())
{
    Console.WriteLine((string)t["ref_id"]);
}

but of course that doesn't work. All the examples work great if you know the key while writing your code. It breaks down when you don't know the key in advance.

like image 847
Nathan DeWitt Avatar asked Jan 13 '12 18:01

Nathan DeWitt


People also ask

Can you parse a JSON object?

parse() JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

Can C read JSON files?

The website states the following: Jansson is a C library for encoding, decoding and manipulating JSON data. It features: Simple and intuitive API and data model. Can both encode to and decode from JSON.

What is cJSON in C?

cJSON aims to be the dumbest possible parser that you can get your job done with. It's a single file of C, and a single header file. JSON is described best here: http://www.json.org/ It's like XML, but fat-free. You use it to move data around, store things, or just generally represent your program's state.

How do I convert a JSON file to readable?

If you need to convert a file containing Json text to a readable format, you need to convert that to an Object and implement toString() method(assuming converting to Java object) to print or write to another file in a much readabe format. You can use any Json API for this, for example Jackson JSON API.


2 Answers

It's doable; this works but it's not elegant. I'm sure there's a better way.

var o = JObject.Parse(yourJsonString);

foreach (JToken child in o.Children())
{
    foreach (JToken grandChild in child)
    {
        foreach (JToken grandGrandChild in grandChild)
        {
            var property = grandGrandChild as JProperty;

            if (property != null)
            {
                Console.WriteLine(property.Name + ":" + property.Value);
            }
        }
    }
}

Prints:

id:910719
type:asdf
ref_id:7568
id:910721
type:asdf
ref_id:7568
id:910723
type:asdf
ref_id:7568
like image 147
TrueWill Avatar answered Sep 21 '22 12:09

TrueWill


You can iterate over the child objects with a simple LINQ query like this:

JObject jFoo = JObject.Parse(json);

foreach (JObject obj in jFoo.Properties().Select(p => p.Value))
{
    Console.WriteLine("id: " + obj["id"]);
    Console.WriteLine("type: " + obj["type"]);
    Console.WriteLine("ref_id: " + obj["ref_id"]);
}

Fiddle: https://dotnetfiddle.net/fwINPa

Or if you just want all the ref_id values, you can do something like this:

string[] refIds = jFoo.Properties()
                      .Select(p => (string)p.Value["ref_id"])
                      .ToArray();

Console.Write(string.Join("\r\n", refIds));

Fiddle: https://dotnetfiddle.net/twOuVY

like image 20
Brian Rogers Avatar answered Sep 25 '22 12:09

Brian Rogers