1

I have a Json file with couple of fields and I have some problems searching for specific fields.

This is the Json file(I cut it short since the original is huge):

{
  "errors": {
    "errorCode": 0,
    "errorMessage": "",
    "errorDescription": null
  },
  "pagination": {
    "recordsReturned": 250,
    "totalRecordsFound": 123,
    "currentPage": 1,
    "recordsPerPage": 250
  },
  "data": {
    "totalDCount": 1713,
    "totalValue": "50",
    "totalCarats": 60,
    "averagePricePerCarat": 21,
    "averageDiscount": -0.29,
    "dResult": [
      {
        "color": "H",
        "dID": 4693,
        "fancyColor": {
          "dominantColor": null,
          "secondaryColor": null,
          "overtones": null,
          "intensity": null,
          "color1": null,
          "color2": null
        },
        "seller": {
          "accountID": 124,
          "companyName": "",
          "companyCode": " ",
          "founded": "",
          "address": null,
          "telephone": " ",
          "fax": null,
          "email": null,
          "contactPrimaryName": "value",
          "city": null,
          "state": null,
          "country": "USA",
          "address1": null,
          "address2": null,
          "skypeName": null,
          "primarySupplierBadge": true,
          "ratingPercent": 1.0,
          "totalRating": 1.0,
          "relatedAccounts": null
        },

          "shape": "Round",
          {
        "color": "H",
        "dID": 46,
        "fancyColor": {
          "dominantColor": null,
          "secondaryColor": null,
          "overtones": null,
          "intensity": null,
          "color1": null,
          "color2": null
        },
        "seller": {
          "accountID": 124,
          "companyName": "",
          "companyCode": " ",
          "founded": "",
          "address": null,
          "telephone": " ",
          "fax": null,
          "email": null,
          "contactPrimaryName": "value",
          "city": null,
          "state": null,
          "country": "USA",
          "address1": null,
          "address2": null,
          "skypeName": null,
          "primarySupplierBadge": true,
          "ratingPercent": 1.0,
          "totalRating": 1.0,
          "relatedAccounts": null
        },

          "shape": "Round" 

      }
    ]
  }
}

I wrote a code that should search for "dId" field value under the "dResult". Unfortunately this error comes up (I am using Newtonsoft.Json parser) :

"Newtonsoft.Json.JsonReaderException: Invalid property identifier character: {. Path 'data.dResult[0].shape', line 54, position 11."

A.This is the code I wrote, I would be happy if you could tell me what is the problem ?

B.A second problem that I had is that I need to pick only the "dID" of those that have the "shape" field value as "Round", I didn't figure out a way to do that since I need to go and find a further field while encountering "dId" field .

  class Program
{
    static void Main(string[] args)
    {
        string filepath = "../../json1.json";
        string result = string.Empty;
        string str = string.Empty;
        using (StreamReader r = new StreamReader(filepath))
        {


            var json = r.ReadToEnd();


            JObject jObject = JObject.Parse(json);
            JToken jUser = jObject["data"];
            string jsonString = jUser.ToString();
            JObject jObject1 = JObject.Parse(jsonString);

            JToken jUser2 = jObject1["dResult"];

            string jsonString2 = jUser2.ToString();
            JObject jObject2 = JObject.Parse(jsonString2);


            foreach (var item in jObject2.Properties())
                {

                if (item.Name == "dID")
                {
                    str = item.Value.ToString();

                            result = result + " " + str;
                }

        }

    }

        Console.WriteLine(result);

    }
}

Reference for the comment I received here (Another Json section, this is under "dResult"):

, {
        "dID": 281242,
        "seller": {
            "accountID": 21321,
            "companyName": "RA",
            "companyCode": "001",
            "founded": "000",
            "address": null,
            "telephone": "999",
            "fax": null,
            "email": null,
            "contactPrimaryName": "name",
            "city": null,
            "state": null,
            "country": "USA",
            "address1": null,
            "address2": null,
            "skypeName": null,
            "primarySupplierBadge": true,
            "ratingPercent": 1.0,
            "totalRating": 1.0,
            "relatedAccounts": null
        },
        "shape": "Round",
        "size": 0.010,
        "color": "K",
        "fancyColor": {
            "dominantColor": null,
            "secondaryColor": null,
            "overtones": null,
            "intensity": null,
            "color1": null,
            "color2": null
        },
5
  • The problem is that the { block which follows "shape" needs an identifier (key). The others have ones like "seller", "dResult" and "fancycolor". It looks like maybe you messed it up when you edited it for length. Commented Nov 20, 2018 at 18:57
  • Hi, I am adding to the question another section of the Json, it doesn't seem like shape have a key like you mentioned. Commented Nov 20, 2018 at 19:04
  • 1
    Not sure why you need to re-parse. jObject["data"]["dResult"][0]["dID"] should work. Commented Nov 20, 2018 at 19:08
  • Then how can I print the "dID" that it matching "shape" is round ? How can I access the shape field and set this condition at this point ? I changed the Json parsing for this syntax now: JObject jObject = JObject.Parse(json); JToken jUser = jObject["data"]["dResult"][0]["dID"]; Commented Nov 20, 2018 at 19:23
  • You can use Linq to query all objects that are round: from r in jObject["data"]["dResult"] where r["shape"].ToString() == "Round" select r; Commented Nov 20, 2018 at 19:57

2 Answers 2

2

You can use the following Linq query to pull the dID values for the Round shapes. However the JSON is not in a correct format.

var jsonStr = File.ReadAllText(Path.Combine(
    Environment.GetFolderPath(Environment.SpecialFolder.Desktop), 
    "example-json.json"));

var parsed = JObject.Parse(jsonStr);

var dIdList = parsed["data"]["dResult"]
    .Where(x => x.Value<String>("shape").Equals("round", StringComparison.InvariantCultureIgnoreCase))
    .Select(x => x.Value<Int32>("dID"))
    .ToList();

And here is the re-formatted JSON (notice the diff on line 52-53), there was a missing } which caused the array to be off:

enter image description here

Once you correct the JSON, by adding this } and run the above Linq query it will return the following result:

enter image description here

Good, luck. Let me know if you need any further assistance.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, given that the Json I posted is the source that I got, there is diffidently a structural problem with it ?
What is the main difference between where "shape" was and where you moved it ?
Moving the "shape": "round" property is not necessary, but it helped me line up the items in the dResult array. The problem was in the dResult array. Notice that in your original json there is only 1 element in that array. There should have been 2. Basically on line 52, right after the first "shape": "round" you are missing a } to close the first element of the array.
0

Once you fix the improperly formatted json data, you can use linq to find the round objects:

var searchResults = from r in jObject["data"]["dResult"]
                    where r["shape"].ToString() == "Round"
                    select r;

foreach (var r in searchResults)
{
    Console.WriteLine(r["dID"]);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.