0

I am trying to search a json file with a string and then return a value from the same object as that string. This is a part of the json file:

    [
      "7c6b2f",
      "EYZ",
      "Australia",
      1611990353,
      1611990419,
      144.8364,
      -37.6611,
      13114.02,
      false,
      50.42,
      171.56,
      null,
      null,
      null,
      "5064",
      true,
      0
    ],
    [
      "7c6b0c",
      "JST",
      "New-Zealand",
      1611990440,
      1611990440,
      148.4636,
      -33.7973,
      10668,
      false,
      248.2,
      37.84,
      -0.33,
      null,
      11170.92,
      "1461",
      false,
      0
    ] 

I want to have it so that if the user enters EYZ then the code will return Australia. I am currently setting the json file to a string but I am not sure how you would create objects to search in this scenario.

Sedgie
  • 1

2 Answers2

1

First of all, this is not a valid json file. You need to enclose it in an array element:

[
  [
     "xyz"
     ...
  ],
  [
  ]
]

Once your object is valid, you can you the JSON.Net library to parse it in your code

// Here you'll have your value
string json = @"[
  'Small',
  'Medium',
  'Large'
]";

JArray a = JArray.Parse(json);

And you can see How to access elements of a JArray (or iterate over them) how to iterate/access them.

Athanasios Kataras
  • 25,191
  • 4
  • 32
  • 61
0

JSON.Net

    public static string Search(string input)
    {
        using (var sr = new StreamReader("your.json"))
        {
            var reader = new JsonTextReader(sr);
            while (reader.Read())
            {
                if (reader.TokenType==JsonToken.String)
                {
                    var value = reader.ReadAsString();
                    if (value == input)
                    {
                        return reader.ReadAsString();
                    }
                }
            }
        }
        return null;
     }

SystemExtensions.Core

public static string Search(string input)
{
    using (var sr = new StreamReader("your.json"))
    {
        var reader = JsonReader.CreateJson5(sr, 2048);
        while (reader.Read())
        {
            if (reader.IsString)
            {
                var value = reader.GetString();
                if (value == input)
                {
                    if (reader.Read() && reader.IsString)
                    {
                        return reader.GetString();
                    }
                }
            }
        }
    }
    return null;
 }