0

As the following string, use json_decode to convert it into an array. However, after conversion, the value of TbManager:userAccesses[] is still a string.

TbManager:userAccesses[] could be converted to array by calling json_decode again for it, json_decode($json['TbManager:userAccesses[]']), but how to convert it in the first json_decode call?

$json = '{
"TbUser:username":"admin",
"TbManager:userAccesses[]":"[\"1\",\"8\"]"
}'

// converted to JSON with 'TbManager:userAccesses[]':string
// how to conver TbManager:userAccesses[] as array type
$json = json_decode($json)

4 Answers 4

2
"TbManager:userAccesses[]":"[\"1\",\"8\"]"

Over there this is a single value "[\"1\",\"8\"]" it is not an array according to JSON syntax, hence the output you see.

Array would be when the value is like

$json = '{
"TbUser:username":"admin",
"TbManager:userAccesses":[1,8]
}';
Sign up to request clarification or add additional context in comments.

2 Comments

the output of TbManager:userAccesses[] after json_decode is ["1", "8"], and also, if 1, 8 are in string, how to declare TbManager:userAccesses[] in string? by using single quote?
I see, it is because of the quotation of [ ], since there is an quotation the processor use it as a string
1

It's because your JSON data have bad format. The right format of your JSON data:

{"TbUser:username":"admin","TbManager:userAccesses[]":[1,8]}

in your code it will be:

$json = '{
"TbUser:username":"admin",
"TbManager:userAccesses[]":[1,8]
}';

And then:

var_dump($json);

will output:

object(stdClass)#1 (2) {
  ["TbUser:username"] => string(5) "admin"
  ["TbManager:userAccesses[]"] => array(2) {
    [0] => int(1)
    [1] => int(8)
  }
}

2 Comments

Bad or not fit for the purpose Format?
not fit for the purpose sounds better :/
1

Your $json should look like

{"TbUser:username":"admin","TbManager:userAccesses[]":[1,8]}"

In this case 'TbManager:userAccesses[]' will be array after json_decode

Comments

0

As mentioned above, it's not a valid json string, but if that's what you get, here's a snippet that would convert those values to array:

$json = '{
    "TbUser:username":"admin",
    "TbManager:userAccesses[]":"[\"1\",\"8\"]"
}';

$json = json_decode($json);

array_walk_recursive($json, function (&$item, $key)
{
    if (substr($key, -2) == '[]') {
        $item = json_decode($item);  
    }
});

print_r($json);

Comments

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.