Home > database >  Find entry in JSON (Kraken.com uncommon JSON format)
Find entry in JSON (Kraken.com uncommon JSON format)

Time:11-24

I need to find if a string exists in JSON Kraken.com retrieved file: I get it this way:

$sURL = "https://api.kraken.com/0/public/OHLC?pair=ETHAED&interval=5&since=". strtotime("-1 day");

$ch = curl_init();

$config['useragent'] = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0';

curl_setopt($ch, CURLOPT_USERAGENT, $config['useragent']);

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

curl_setopt($ch, CURLOPT_URL, $sURL);

$result = curl_exec($ch);

curl_close($ch);

$obj = json_decode($result, true);

Sometimes pairs names differ from URL string and JSON (i.e. I can write LTCEUR but in JSON I see LTCZEUR

So I need to check if the string does exists in the $obj

$sName = "ETHAED";

print_r($obj);

if (in_array($sName,$obj)){

    echo("Found ".$sName."<br>");

}else{

    echo("NOT FOUND"."<br>");

}

but this doesn't work.

if I do a print_r() I can clearly see the pair name, but can't verify it. Any suggestion?

Kraken.com JSON is not standard so I can't easily retrieve the name of the PAIR, I tried all possible combinations of $obj["result"][$sName] but without result.

Example: https://api.kraken.com/0/public/OHLC?pair=LTCUSD Here pair is LTCUSD

But on Json:

{"error":[],"result":{"XLTCZUSD":[[1669197540,"78.74","78.74","78.58","78.59","78.59","23.82168114",8]

CodePudding user response:

Something is wrong with your comparison.

in_array($sName,$obj)

Should be:

is_array($obj['result'][$sName] ?? null)

Caveat: Read that carefully; it's now is instead of in.

Or, if you don't care if it's null, a string, or non-array:

array_key_exists($obj['result'], $sName)

Detailed explanation

in_array($sName,$obj) is checking if $sName matches (== equality) any of the elements in the first level of your array.

Since the first level of the array looks like this (pseudocode here):

error => []
result => [
    XLTCZUSD => [...]
    last: 123456
]

Since 'ETHAED' is neither [] nor is it [XLTCZUSD => [...],last: 123456] it doesn't match anything.

CodePudding user response:

Yes it works perfectly. Just a little correction on format:

if (array_key_exists($sName, $obj['result'])){
echo("FOUND ".$sName."<br>");           
}else{
echo("ERROR ".$sName."<br>"); 
}
  • Related