Can someone see the error of my JSON ways

I have an API query that returns almost valid JSON. All the keys are unquoted which I think makes it bad JSON. I have no control over the JSON returned by the API. All the keys will always be the same. Rather than coming up with some regex search and replace, I decided to just search for each unquoted key name and replace it with a double quoted one. To test, I created a search for the first key and ran the API query again. This time, all the keys were double quoted like they should have been in the first place, except for the first key which was double double quoted as in ““FirstKey””.
I am baffled. I am at a very beginner level here and have no idea where to turn.

Many thanks for reading

So how do you check the response? Do you print out the string or the already decoded object? Maybe it is just an issue of output?

This is my query

<?php

$url = "https://www.example.com/drupal_interface/zip9Lookup";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Content-Type: application/json",
   "Authorization: Basic DhQN1RWeUZrVTdEeEp1",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$data = '{"searchType":"ZIP","paramMap":{"zip9":"554161812"}}';

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

//for debug only!
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
echo ($resp);
print_r('</pre>');
?>

And this is the response.

{
searchType: "ZIP",
paramMap: {
zip9: "554161812"
},
resultList: [
{
rate: "6.875%",
desc: "MN State"
},
{
rate: "0.150%",
desc: "Hennepin County"
},
{
rate: "0.500%",
desc: "Hennepin County Transit"
},
{
total_rate_desc: "Total Rate",
total_rate: "7.525%"
}
],
errorCode: 0,
errorDesc: "No Error."
}

If I add

OOPS

?php

$url = "https://www.example.com/drupal_interface/zip9Lookup";

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

$headers = array(
   "Content-Type: application/json",
   "Authorization: Basic U1VUVGVzdDAwMjI6cDhQN1RWeUZrVTdEeEp1",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);

$data = '{"searchType":"ZIP","paramMap":{"zip9":"554161812"}}';

curl_setopt($curl, CURLOPT_POSTFIELDS, $data);

//for debug only!
//curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
//curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$resp = curl_exec($curl);
curl_close($curl);
$test = str_replace('searchType','"searchType"',$resp);

echo ($test;
print_r('</pre>');


?>

So maybe the easiest way is to use JSON5?

I will give that a look. Thanks

I guess the json response was valid after all. When I do a json_decode I get the following array

Array
(
    [searchType] => ZIP
    [paramMap] => Array
        (
            [zip9] => 554161812
        )

    [resultList] => Array
        (
            [0] => Array
                (
                    [rate] => 6.875%
                    [desc] => MN State
                )

            [1] => Array
                (
                    [rate] => 0.150%
                    [desc] => Hennepin County
                )

            [2] => Array
                (
                    [rate] => 0.500%
                    [desc] => Hennepin County Transit
                )

            [3] => Array
                (
                    [total_rate_desc] => Total Rate
                    [total_rate] => 7.525%
                )

        )

    [errorCode] => 0
    [errorDesc] => No Error.
)

My eyes have glazed over after all my reading and trying examples on retrieving individual elements of the array. I am after the value for [total_rate] Can someone at least give me some hints.

Thanks

you should get it with:

yourObject->resultList[3]->total_rate

but be careful. First be sure that the total rate is always at index 3 in the json object.
At the end the JSON is not very good structured at all. I would never use it in my applications.

It’s an array, so the syntax should be

$data['resultList'][3]['total_rate']

If total_rate is always in the last element of resultList this might be better:

$resultList = $data['resultList'];
$totalRate = $resultList[count($resultList) - 1]['total_rate'];

Agreed!

Many thanks all. I was close.
In this case, I have no choice about using json. It is the result of an API query to the state for very local sales tax rates. According to the documentation, it will always be structured the same, but noted and will need to test random rural locations to make sure.
In addition to lots of reading and searching, I did some YouTube videos last night trying to understand reading data in multi-dimensional arrays.

Again, thank you both.

I just wanted to follow up. As warned, there is a case where the total_rate is not index 3. I added a foreach loop

forEach($data['resultList'] as $element){
   if ($element['total_rate']){
     print_r($element['total_rate']);
    }
}

It seems to give me what I want even though it throws an error about the undefined total_rate.
I am going to move on for now and tackle errors after I am further down the road with this.
Again, I want to thank you both

That would be a warning, not an error, and can be mitigated by using isset

foreach ($data['resultList'] as $element) {
   if (isset($element['total_rate'])) {
     print_r($element['total_rate']);
    }
}

or alternatively array_key_exists

foreach ($data['resultList'] as $element) {
   if (array_key_exists('total_rate', $element)) {
     print_r($element['total_rate']);
    }
}

The main difference being that isset returns false if the key is set but the value is falsey (zero, empty string, null, false, etc) whereas array_key_exists will still return true in that case.

I used error “in error” and did mean to use warning. :grin: I still have so much to learn, I have been using Linux for close to 30 years. I don’t remember when I first picked up PHP but it was a long time ago. I use it for some project and then need to set it aside for something else so I never become proficient. It is always fun to get back into it though.
Thanks for the fix.

1 Like