Royi Namir
Royi Namir

Reputation: 148744

Find value via property name in json.net?

I have this simple json response :

   {
    "results": [
        {
            "address_components": [
                {
                    "long_name": "277",
                    "short_name": "277",
                    "types": [
                        "street_number"
                    ]
                },
                {
                    "long_name": "United States",
                    "short_name": "US",
                    "types": [
                        "country",
                        "political"
                    ]
                },
                {
                    "long_name": "11211",
                    "short_name": "11211",
                    "types": [
                        "postal_code"
                    ]
                }
            ],
            "formatted_address": "277 Bedford Avenue, Brooklyn, NY 11211, USA"
        },
        {
            "a": 2
        }
    ],
    "status": "OK"
}

How can I get the green value according to (yellow) types which contains "country" ?

visualization :

enter image description here

Is it possible to do it via json Linq ? (Newtonsoft.Json.Linq.JObjec)

Something like this psuedo : ( doesn't work/compile)

 JObject jt=   JObject.Parse(dataObjects);
 jt["results"].Where(f=>f.key=="address_components").Where(g=>g["types"].contains("country")).select(h=>h["long_name")

Upvotes: 2

Views: 6434

Answers (1)

MichaelS
MichaelS

Reputation: 3831

Yes, that's possible.

jt["results"].Children()
    .Select(t => t["address_components"])
    .Where(a => a != null)
    .Children()
    .Where(c => c["types"].Children().Contains("country"))
    .Select(a => a["long_name"])
    .ToArray();

Upvotes: 6

Related Questions