Home > Blockchain >  How to properly query a Json Object with SelectToken
How to properly query a Json Object with SelectToken

Time:10-27

I have a JSON object like in below.

{
  "?xml": {
    "@version": "1.0",
    "@encoding": "UTF-8"
  },
  "?xml-stylesheet": "type=\"text/xsl\" href=\"isokur.xsl\"",
  "Tarih_Date": {
    "@Tarih": "14.10.2022",
    "@Date": "10/14/2022",
    "@Bulten_No": "2022/196",
    "Currency": [
      {
        "@CrossOrder": "0",
        "@Kod": "USD",
        "@CurrencyCode": "USD",
        "Unit": "1",
        "Isim": "ABD DOLARI",
        "CurrencyName": "US DOLLAR",
        "ForexBuying": "18.5596",
        "ForexSelling": "18.5930",
        "BanknoteBuying": "18.5466",
        "BanknoteSelling": "18.6209",
        "CrossRateUSD": null,
        "CrossRateOther": null
      },
      {
        "@CrossOrder": "1",
        "@Kod": "AUD",
        "@CurrencyCode": "AUD",
        "Unit": "1",
        "Isim": "AVUSTRALYA DOLARI",
        "CurrencyName": "AUSTRALIAN DOLLAR",
        "ForexBuying": "11.6732",
        "ForexSelling": "11.7493",
        "BanknoteBuying": "11.6195",
        "BanknoteSelling": "11.8198",
        "CrossRateUSD": "1.5862",
        "CrossRateOther": null
      }
    ]
  }
}

And I want to grab only the this part from it. Where @CurrencyCode == "USD"

[
      {
        "@CrossOrder": "0",
        "@Kod": "USD",
        "@CurrencyCode": "USD",
        "Unit": "1",
        "Isim": "ABD DOLARI",
        "CurrencyName": "US DOLLAR",
        "ForexBuying": "18.5596",
        "ForexSelling": "18.5930",
        "BanknoteBuying": "18.5466",
        "BanknoteSelling": "18.6209",
        "CrossRateUSD": null,
        "CrossRateOther": null
      }
]

For this purpose, I created the code below according to this answer.

string result = JObject.Parse(json)["Tarih_Date"].SelectToken("$.Currency[?(@.@CurrencyCode=='USD')]")["Currency"].ToString();

But I couldn't make it word and I get the exception below. As I understand, my query doesn't find it's way(?) But couldn't understand where it is.

System.NullReferenceException: 'Object reference not set to an instance of an object.'

Anything helps!

CodePudding user response:

You get the exception because there is no property called Currency in the output of SelectToken. You will get the desired output by switching to:

var result = JObject.Parse(json)["Tarih_Date"].SelectToken("$.Currency[?(@.@CurrencyCode == 'USD')]");

  • Related