Application Programming Interfaces C#

Select JSON Tokens with Newtonsoft

This C# program demonstrates how to select tokens from a JSON document with the Newtonsoft Json package. Newtonsoft.json is a Nuget package that must be installed in order to run this program.

Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
// Requires Nuget Newtonsoft.Json package
using Newtonsoft.Json.Linq;

namespace SelectingNodes
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string sBibleJson = @"{ ""Bible"": [
                {
                    ""Old Testament"": {
                        ""Content"": {
                            ""Pentateuch"": [
                                { ""Name"": ""Genesis"",
                                  ""Chapters"": ""50""
                                },
                                { ""Name"": ""Exodus"",
                                  ""Chapters"": ""40""
                                },
                                { ""Name"": ""Leviticus"",
                                  ""Chapters"": ""27""
                                },
                                ""Numbers"",
                                ""Deuteronomy""
                            ],
                            ""Historical"": [
                                ""Joshua"",
                                ""Judges""
                            ]
                        }
                    }
                },
                {
                    ""New Testament"": {
                        ""Content"": {
                            ""Gospels"": [
                                { ""Name"": ""Matthew"", 
                                  ""Chapters"": ""28""
                                },
                                { ""Name"": ""Mark"",
                                  ""Chapters"": ""16""
                                },
                                ""Luke"",
                                { ""Name"": ""John"",
                                  ""Chapters"": ""21""
                                }
                            ]
                        }
                    }
                }
            ]}";
            JObject qJObjectBible = JObject.Parse(sBibleJson);

            // Print the entire document
            Console.WriteLine("-------------------THE ENTIRE DOCUMENT-------------------");
            Console.WriteLine(qJObjectBible.ToString());

            // Select a single token via path
            Console.WriteLine("-------------------SELECT THE OLD TESTAMENT WITH AN INDEX-------------------");
            Console.WriteLine(qJObjectBible.SelectToken("Bible[0]").ToString());

            // Get the element with the historical books of the Old Testament
            Console.WriteLine("-------------------SELECT THE HISTORICAL BOOKS-------------------");
            Console.WriteLine(qJObjectBible.SelectToken("Bible[0]['Old Testament'].Content.Historical").ToString());

            // Linq queries
            // Get the books of the Pentateuch that have 30 or more chapter
            Console.WriteLine("-------------------SELECT BOOKS OF THE PENTATEUCH WITH 30 OR MORE CHAPTERS-------------------");
            IEnumerable<JToken> qaLargeBooks = qJObjectBible.SelectTokens("$..Pentateuch[?(@.Chapters >= 30)].Name");
            foreach (JToken qBook in qaLargeBooks)
            {
                Console.WriteLine(qBook);
            }


            // Display the paths of the content elements
            Console.WriteLine("-------------------DISPLAY CONTENT ELEMENT PATH VALUES-------------------");
            IList<JToken> qaContentList = qJObjectBible.SelectTokens("..Content").ToList();
            foreach (JToken qContent in qaContentList)
            {
                Console.WriteLine(qContent.Path);
            }


            // Get the names of all of the books of the Pentateuch that are objects with a name property
            Console.WriteLine("-------------------SELECT BOOKS OF THE PENTATEUCH WITH A NAME PROPERTY-------------------");
            var qaPentBookNames = from p in qJObjectBible["Bible"][0]["Old Testament"]["Content"]["Pentateuch"]
                              where p.Type != JTokenType.String
                              select (string)p["Name"];
            foreach (JToken qBookName in qaPentBookNames)
            {
                Console.WriteLine(qBookName);
            }


            // Get the names of all of the books of the Bible that are objects with a name property
            Console.WriteLine("-------------------SELECT BOOK NAMES OF THE BIBLE ALPHABETICALLY-------------------");
            var qaBookNames = from p in qJObjectBible.SelectTokens("$..Content[?(@..Name != '')]").Children().Values()
                              where p.Type != JTokenType.String
                              orderby p["Name"] ascending
                              select (string)p["Name"];
            foreach (JToken qBookName in qaBookNames)
            {
                Console.WriteLine(qBookName);
            }
        }
    }
}
 

Output

-------------------THE ENTIRE DOCUMENT-------------------
{
  "Bible": [
    {
      "Old Testament": {
        "Content": {
          "Pentateuch": [
            {
              "Name": "Genesis",
              "Chapters": "50"
            },
            {
              "Name": "Exodus",
              "Chapters": "40"
            },
            {
              "Name": "Leviticus",
              "Chapters": "27"
            },
            "Numbers",
            "Deuteronomy"
          ],
          "Historical": [
            "Joshua",
            "Judges"
          ]
        }
      }
    },
    {
      "New Testament": {
        "Content": {
          "Gospels": [
            {
              "Name": "Matthew",
              "Chapters": "28"
            },
            {
              "Name": "Mark",
              "Chapters": "16"
            },
            "Luke",
            {
              "Name": "John",
              "Chapters": "21"
            }
          ]
        }
      }
    }
  ]
}
-------------------SELECT THE OLD TESTAMENT WITH AN INDEX-------------------
{
  "Old Testament": {
    "Content": {
      "Pentateuch": [
        {
          "Name": "Genesis",
          "Chapters": "50"
        },
        {
          "Name": "Exodus",
          "Chapters": "40"
        },
        {
          "Name": "Leviticus",
          "Chapters": "27"
        },
        "Numbers",
        "Deuteronomy"
      ],
      "Historical": [
        "Joshua",
        "Judges"
      ]
    }
  }
}
-------------------SELECT THE HISTORICAL BOOKS-------------------
[
  "Joshua",
  "Judges"
]
-------------------SELECT BOOKS OF THE PENTATEUCH WITH 30 OR MORE CHAPTERS-------------------
Genesis
Exodus
-------------------DISPLAY CONTENT ELEMENT PATH VALUES-------------------
Bible[0]['Old Testament'].Content
Bible[1]['New Testament'].Content
-------------------SELECT BOOKS OF THE PENTATEUCH WITH A NAME PROPERTY-------------------
Genesis
Exodus
Leviticus
-------------------SELECT BOOK NAMES OF THE BIBLE ALPHABETICALLY-------------------
Exodus
Genesis
John
Leviticus
Mark
Matthew
Press any key to continue . . .
 
 

© 2007–2025 XoaX.net LLC. All rights reserved.