Joy Cooper Joy Cooper - 4 months ago 9
JSON Question

Get Json Object from external URL with PHP

I have an URL that returns the JSON object below:

{ "addressList": { "addresses": [ { "id": 0000000, "receiverName": "Name Example", "country": { "id": "BRA", "name": "Brasil" }, "state": { "id": "SP" }, "city": "São Paulo", "zipcode": "00000000", "type": "Residential", "street": "000, St Example", "number": 00, "neighborhood": "Example", "hash": "1bf09357", "defaultAddress": false, "notReceiver": false } ] } }


I want to get the
state
value, how can I retrieve that with PHP?

I tried, something like this, but I couldn't get the
state
value, that should be
SP
in this case.

$string = '{ "addressList": { "addresses": [ { "id": xxxxxx, "receiverName": "XXXXX XXXXX", "country": { "id": "BRA", "name": "Brasil" }, "state": { "id": "SP" }, "city": "São Paulo", "zipcode": "03164xxx", "type": "Residential", "street": "Rua xxx", "number": xx, "neighborhood": "xxxxx", "hash": "xxxxx", "defaultAddress": false, "notReceiver": false } ] } }';

$json_o = json_decode($string);

$estado = $json_o->state;


How can I achieve the result I want?

Answer

Your JSON is not valid - you can validate it on jsonlint.com (it's invalid due to incorrectly formatted numeric values - "id" : 000000).

From then on, you can decode the value and access your data:

$json_o = json_decode($string);

$estado = $json_o->addressList->addresses[0]->state->id;

If you don't have access to the code that generates the JSON, you can attempt to run a regex to match, replace & wrap the numerical values with ":

$valid_json = preg_replace("/\b(\d+)\b/", '"${1}"', $str);

Note: The above is just an example - you'll have to figure out a case where a numerical value is already wrapped by ".

Comments