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.
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.
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.
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.
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. 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.