Trying to read in Json Data :/

FlamingMongo

New member
Joined
Apr 27, 2023
Messages
4
Programming Experience
1-3
Could I get some assistance on this?
I'm trying to read in Json data and just output a line to console
C#:
   [Test]
        public void Test5()
        {
            string fileName = @"C:\Users\blah\source\repos\cars.cs";
            JObject Obj = JObject.Parse(File.ReadAllText(fileName));
            string rssTitle = (string)Obj["cars"]["brand"];
            Console.WriteLine(rssTitle);


        }
However on the JObject Obj line my compiler says
C#:
 Message: 
Newtonsoft.Json.JsonReaderException : Error parsing undefined value. Path '', line 1, position 1.

  Stack Trace: 
JsonTextReader.ParseUndefined()
JsonTextReader.ParseValue()
JObject.Load(JsonReader reader, JsonLoadSettings settings)
JObject.Parse(String json, JsonLoadSettings settings)
JObject.Parse(String json)
Tests.Test5() line 102
 
Look closely at your line 4. It looks like you are trying to load a C# file, not a JSON file, so the JSON parser is complaining that the file is not the right format.
 
Look closely at your line 4. It looks like you are trying to load a C# file, not a JSON file, so the JSON parser is complaining that the file is not the right format.

Thanks I change to this
C#:
 string fileName = @"C:\Users\user\source\repos\cars.json";
            JObject Obj = JObject.Parse(File.ReadAllText(fileName).ToString());
            string brand = (string)Obj[0][0];
            Console.WriteLine("Brand equals: " + brand);

and I'm now getting this
C#:
  Message: 
System.ArgumentException : Accessed JObject values with invalid key value: 0. Object property name expected.

  Stack Trace: 
JObject.get_Item(Object key)
Tests.Test5() line 97

And the json file looks like
C#:
{
  "cars": [
    {
      "brand": "Toyo",
      "models": [
        {
          "model": "car_model_1",
          "basePrice": 18000,
          "colors": [
            "red",
            "white",
            "blue"
          ]
        },
        {
          "model": "car_model_2",
          "colors": [
            "red",
            "white",
            "blue",
            "gray",
            "sky"
          ]
        },
        {
          "model": "car_model_3",
          "colors": [
            "red",
            "white",
            "blue",
            "green"
          ]
        }
      ]
    },
    {
      "brand": "Hoyo",
      "models": [
        {
          "model": "car_model_hoy_1",
          "basePrice": 18000,
          "colors": [
            "red",
            "white",
            "blue"
          ]
        },
        {
          "model": "car_model_hoy_2",
          "colors": [
            "red",
            "white",
            "blue",
            "yellow",
            "orange"
          ]
        },
        {
          "model": "car_model_hoy_3",
          "basePrice": 32000,
          "colors": [
            "red",
            "white",
            "blue",
            "orange",
            "brown",
            "yellow",
            "purple"
          ]
        },
        {
          "model": "car_model_hoy_4",
          "basePrice": 34500,
          "colors": [
            "red",
            "white",
            "blue",
            "orange",
            "brown"
          ]
        },
        {
          "model": "car_model_hoy_5",
          "basePrice": 37000,
          "colors": [
            "red",
            "white",
            "blue",
            "orange",
            "brown"
          ]
        },
        {
          "model": "car_model_hoy_6",
          "basePrice": 54000,
          "colors": [
            "blue",
            "orange",
            "brown",
            "white"
          ]
        }
      ]
    }
  ],
  "trucks": [
    {
      "brand": "Toyo",
      "models": [
        {
          "model": "truck_model_1",
          "basePrice": 18000,
          "colors": [
            "red",
            "white",
            "blue"
          ]
        },
        {
          "model": "truck_model_2",
          "colors": [
            "red",
            "white",
            "blue",
            "gray",
            "sky"
          ]
        },
        {
          "model": "truck_model_3",
          "colors": [
            "red",
            "white",
            "blue",
            "green"
          ]
        }
      ]
    },
    {
      "brand": "Hoyo",
      "models": [
        {
          "model": "truck_model_hoy_1",
          "basePrice": 18000,
          "colors": [
            "red",
            "white",
            "blue"
          ]
        },
        {
          "model": "truck_model_hoy_2",
          "colors": [
            "red",
            "white",
            "blue",
            "yellow",
            "orange"
          ]
        },
        {
          "model": "truck_model_hoy_3",
          "basePrice": 32000,
          "colors": [
            "red",
            "white",
            "blue",
            "orange",
            "brown",
            "yellow",
            "purple"
          ]
        },
        {
          "model": "truck_model_hoy_4",
          "basePrice": 34500,
          "colors": [
            "red",
            "white",
            "blue",
            "orange",
            "brown"
          ]
        },
        {
          "model": "truck_model_hoy_5",
          "basePrice": 37000,
          "colors": [
            "red",
            "white",
            "blue",
            "orange",
            "brown"
          ]
        },
        {
          "model": "truck_model_hoy_6",
          "basePrice": 54000,
          "colors": [
            "blue",
            "orange",
            "brown",
            "white"
          ]
        }
      ]
    }
  ]
}
 
I've also tried accessing by using


C#:
       string fileName = @"C:\Users\rixa\source\repos\Aveva\Aveva\cars.json";
            JObject Obj = JObject.Parse(File.ReadAllText(fileName).ToString());
            string brand = (string)Obj["cars"]["brand"];
            Console.WriteLine("Brand equals: " + brand);

With error
C#:
  Message: 
System.ArgumentException : Accessed JArray values with invalid key value: "brand". Int32 array index expected.

  Stack Trace: 
JArray.get_Item(Object key)
Tests.Test5() line 97
 
In Json { } means object and [ ] means array.
Your json object has two properties, "cars" and "trucks", both contains arrays.
I haven't used Newtonsoft for json in a while, but Obj["cars"][0]["brand"] should return the brand for first car object. [0] means the first array element that property ["cars"] returns.
 
In Json { } means object and [ ] means array.
Your json object has two properties, "cars" and "trucks", both contains arrays.
I haven't used Newtonsoft for json in a while, but Obj["cars"][0]["brand"] should return the brand for first car object. [0] means the first array element that property ["cars"] returns.

Thanks a lot
Using this
C#:
string fileName = @"C:\Users\user\source\repos\weather.json";
            JObject Obj = JObject.Parse(File.ReadAllText(fileName).ToString());
            string city = (string)Obj["location"][0]["city"];
            Console.WriteLine("city equals : " + city);
I am now getting this returned on this json file
C#:
 Standard Output: 
city equals : London

How would I return the precipation of day 1 of London though?

I have tried to achieve this by
C#:
            string prec= (string)Obj["location"][3]["forecast"][1]["weather"][2]["precipitation"][0];
which returns
C#:
 Message: 
System.ArgumentOutOfRangeException : Index was out of range. Must be non-negative and less than the size of the collection. (Parameter 'index')

  Stack Trace: 
List`1.get_Item(Int32 index)
JContainer.GetItem(Int32 index)
JArray.get_Item(Object key)
Tests.Test4() line 80

weather.json
C#:
{
  "location": [
    {
      "city": "London",
      "coordinates": {
        "longitude": -0.118092,
        "latitude": 51.509865
      },
      "population": 8982000,
      "country": "GB",
      "forecast": {
        "day_range": 5,
        "weather": [
          {
            "day": 1,
            "temperature": {
              "celsius": 21,
              "fahrenheit": 69.8
            },
            "pressure": 1027,
            "precipitation": {
              "mm": 0,
              "inches": 0
            },
            "wind_speed": {
              "mph": 13.1,
              "kph": 21.08
            },
            "cloud_cover": [
              {
                "description": "Broken",
                "cover_percentage": 10,
                "day_position": "Morning"
              },
              {
                "description": "Broken",
                "cover_percentage": 8,
                "day_position": "Afternoon"
              },
              {
                "description": "Clear",
                "cover_percentage": 0,
                "day_position": "Evening"
              }
            ]
          },
          {
            "day": 2,
            "temperature": {
              "celsius": 18,
              "fahrenheit": 64.4
            },
            "pressure": 998,
            "precipitation": {
              "mm": 8,
              "inches": 0.32
            },
            "wind_speed": {
              "mph": 13.1,
              "kph": 21.08
            },
            "cloud_cover": [
              {
                "description": "Overcast",
                "cover_percentage": 100,
                "day_position": "All day"
              }
            ]
          },
          {
            "day": 3,
            "temperature": {
              "celsius": 27,
              "fahrenheit": 80.6
            },
            "pressure": 756,
            "precipitation": {
              "mm": 15.8,
              "inches": 0.62
            },
            "wind_speed": {
              "mph": 3,
              "kph": 4.83
            },
            "cloud_cover": [
              {
                "description": "Clear",
                "cover_percentage": 0,
                "day_position": "Morning"
              },
              {
                "description": "Scattered",
                "cover_percentage": 47,
                "day_position": "Afternoon"
              },
              {
                "description": "Clear",
                "cover_percentage": 0,
                "day_position": "Evening"
              }
            ]
          },
          {
            "day": 4,
            "temperature": {
              "celsius": 13,
              "fahrenheit": 55.4
            },
            "pressure": 203,
            "precipitation": {
              "mm": 25.2,
              "inches": 0.99
            },
            "wind_speed": {
              "mph": 28.5,
              "kph": 45.87
            },
            "cloud_cover": [
              {
                "description": "DATA_NOT_FOUND",
                "cover_percentage": null,
                "day_position": "Morning"
              },
              {
                "description": "Overcast",
                "cover_percentage": 71,
                "day_position": "Afternoon"
              },
              {
                "description": "Broken",
                "cover_percentage": 26,
                "day_position": "Evening"
              }
            ]
          },
          {
            "day": 5,
            "temperature": {
              "celsius": 5,
              "fahrenheit": 41
            },
            "pressure": 502,
            "precipitation": {
              "mm": 0.2,
              "inches": 0.008
            },
            "wind_speed": {
              "mph": 2.9,
              "kph": 4.67
            },
            "cloud_cover": [
              {
                "description": "Overcast",
                "cover_percentage": 99.8,
                "day_position": "All day"
              }
            ]
          }
        ]
      }
    },
    {
      "city": "New York",
      "coordinates": {
        "longitude": -74.00597,
        "latitude": 40.71427
      },
      "country": "US",
      "forecast": {
        "day_range": 2,
        "weather": [
          {
            "day": 1,
            "temperature": {
              "celsius": 26,
              "fahrenheit": 78.8
            },
            "pressure": 996,
            "precipitation": {
              "mm": 12.7,
              "inches": 0.5
            },
            "wind_speed": {
              "mph": 6,
              "kph": 9.65
            },
            "cloud_cover": [
              {
                "description": "Broken",
                "cover_percentage": 10,
                "day_position": "Morning"
              },
              {
                "description": "Overcast",
                "cover_percentage": 45,
                "day_position": "Afternoon"
              },
              {
                "description": "Overcast",
                "cover_percentage": 65,
                "day_position": "Evening"
              }
            ]
          },
          {
            "day": 2,
            "temperature": {
              "celsius": 22,
              "fahrenheit": 71.6
            },
            "pressure": 1013,
            "precipitation": {
              "mm": 0.51,
              "inches": 0.2
            },
            "wind_speed": {
              "mph": 13.1,
              "kph": 21.08
            },
            "cloud_cover": [
              {
                "description": "Overcast",
                "cover_percentage": 35,
                "day_position": "Morning"
              },
              {
                "description": "Broken",
                "cover_percentage": 14,
                "day_position": "Afternoon"
              },
              {
                "description": "Clear",
                "cover_percentage": 0,
                "day_position": "Evening"
              }
            ]
          }
        ]
      }
    }
  ]
}
 
Try reading the Querying JSON with LINQ section is likely the easiest way to get just "London":
 
So, this is the hard work way to read that file

The easy way is to pop along to Convert JSON to Swift, C#, TypeScript, Objective-C, Go, Java, C++ and more<!-- --> • quicktype and paste your json in

Take the generated c# and read the comment, it will tell you how to real the file and parse it to a c# object rather than a JObject

It will be something like:

C#:
    var x = YourChosenRootName.FromJson(File.ReadAllText(path here));

This means you can then simply do:

C#:
Console.Write(x.Cars.First().Brand);
 
But will the generator be able to handle the case when one of the fields might be an object, or might be a list of that type of object. That is the crux of the problem the OP is running into.
 
Sure:

1683827935857.png



QT.IO's converter is a good chunk smarter than the others I've used; it can cope with that sort of fast-n-loose "sometimes array, sometimes object" BS that scripty folks like to pull :)
 

Latest posts

Back
Top Bottom