AngryHacker
AngryHacker

Reputation: 61616

How to query multiple json nodes?

I have the following json:

{
  "key445" : {
    "text" : "cat",
    "id" : 445
  },
  "key457" : {
    "text" : "mouse",
    "id" : 457
  },
  "key458" : {
    "text" : "rodent",
    "id" : 458
  }
}

I am trying extract text and id into a List<TextIdentifier> (a class with string and an int), or even separately into List<string> and List<int>.

I read the text into JObject using JObject.Parse method. However, I can't figure out how to get to the text and id nodes. I've tried the following but it returns nothing.

var textTokens = o.SelectTokens("/*/text");
var idTokens = o.SelectTokens("/*/id");

How can I get to the tokens I want?

Upvotes: 0

Views: 278

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500745

I would just convert the whole JSON into a Dictionary<string, TextIdentifier> instead of trying to use JsonPath at all:

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;

public class TextIdentifier
{
    public string Text { get; set; }
    public int Id { get; set; }
    public override string ToString() => $"Id: {Id}; Text: {Text}";
}

public class Test
{
    static void Main()
    {
        var json = File.ReadAllText("test.json");
        var dictionary = JsonConvert.DeserializeObject<Dictionary<string, TextIdentifier>>(json);

        foreach (var pair in dictionary)
        {
            Console.WriteLine($"{pair.Key} => {pair.Value}");
        }
    }
}

Output:

key445 => Id: 445; Text: cat
key457 => Id: 457; Text: mouse
key458 => Id: 458; Text: rodent

If you don't care about the keys, you can use dictionary.Values.ToList() to get a List<TextIdentifier> although you shouldn't rely on the order of them.

Upvotes: 2

Related Questions