2

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?

2
  • its under addressList, addresses (first index), state, then id, you can't just outright use state, its not inside the parent level, use print_r / var_dump to find out Commented Jul 12, 2016 at 0:21
  • Note that "octal and hexadecimal formats are not used" for number in JSON. Commented Jul 12, 2016 at 1:05

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

@JoyCooper My pleasure.
1

Your JSON has a couple of syntax errors:

"id":     0000000
"number": 00

JSON doesn't support leading zeros. If precise formatting is important, use strings:

"number": "00"
"id":     "0000000"

Alternatively, use well-formed integers in the JSON (saves space) and convert them to formatted strings in PHP.

Once you've fixed your JSON, you can access the state->id value of the first address as I do below. When you decode JSON from an untrusted source, be prepared to do some error handling:

$json_string ="..."; //your source, to be decoded

$json_o= json_decode($json_string);

if(is_null($json_o)): //there was an error decoding        
    $errno = json_last_error();
    $err_msg = json_last_error_msg();
    die("Json decode failed: Error #$errno: $err_msg");
endif;
//we get here if json_decode succeeded. To get "SP", do...
$stateID = $json_o->addressList->addresses[0]->state->id;

1 Comment

This is a good idea, but it doesn't answer the question of how to access the state field.
0

Try:

$json_o = json_decode($string, true); $estado = $json_o['addressList']['addresses'][0]['state']['id'];

3 Comments

Run echo json_last_error() after json_decode(). What output do you get?
I got just the number 4 as output.
I already got it working with @Darren's answer, thank you anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.