0

I am trying to decode json string that looks like the one below with json_decode php function:

"{id:"1",fields:[{id:"1",value:"asdasd"},{id: "2",value:"asdasd"},{id:"3",value:"asdasd"}]}"

I have tried various options from this question. Like:

$foo = utf8_encode($json_string);
$data = json_decode($foo, true);

Or:

json_decode(str_replace ('\"','"', $json_string), true);

Even with:

json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true );

But, everything I try I always get null. Why is that?

Leff
  • 1,968
  • 24
  • 97
  • 201

3 Answers3

4

First of all, your JSON is invalid. You should always first validate your JSON before asking with any JSON lint tool, which would tell you exactly where and what the error is.

Also, you should always check for errors when handling JSON in PHP. You can check out the json_last_error function's official documentation on how to properly perform the validation.

$json = 'your_json_string';
$array = json_decode($json, true);

if (json_last_error()) {
    die('Invalid JSON provided!');
}

printf('<pre>Valid JSON output: %s</pre>', print_r($array, true));

Worth mentioning: since PHP 7.3 a JSON_THROW_ON_ERROR option was added so the code can be wrapped around with a try-catch block:

try {
    $array = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
    printf('Valid JSON output: %s', print_r($array, true));
} catch (\JsonException $exception) {
    printf('Invalid JSON input: %s', print_r($exception, true));
}

Working example.

Mike Doe
  • 16,349
  • 11
  • 65
  • 88
3
<?php
$data='{
    "id": "1",
    "fields": [{
        "id": "1",
        "value": "asdasd"
    }, {
        "id": "2",
        "value": "asdasd"
    }, {
        "id": "3",
        "value": "asdasd"
    }]
}';

$dataNew=json_decode($data,true);
echo '<pre>';
    print_r($dataNew);

Your json was not valid. The json-keys need to be inside double-quotes. After that json_decode will work fine.

Output is:

Array
(
    [id] => 1
    [fields] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [value] => asdasd
                )

            [1] => Array
                (
                    [id] => 2
                    [value] => asdasd
                )

            [2] => Array
                (
                    [id] => 3
                    [value] => asdasd
                )

        )

)
pr1nc3
  • 8,108
  • 3
  • 23
  • 36
0

Your JSON returns Null because in JSON, the keys should be string.Your JSON format is incorrect and hence returns Null. Try rewriting it as:

 {
  "id":"1",
  "fields":[
    {
      "id":"1",
      "value":"asdasd"

    },
    {
      "id": "2",
      "value":"asdasd"

    },{
      "id":"3",
      "value":"asdasd"
      }
    ]
}
Samudra Deka
  • 101
  • 1
  • 9