简体   繁体   中英

Convert PHP string to JSON array(key:value)

I have the following string that I receive from an API call:

a = "{
      "option1"=>"Color",
      "attribute1"=>{0=>"Black", 1=>"White",2=>"Blue"},
      "option2"=>"Size",
      "attribute2"=>{0=>"S", 1=>"L",2=>"M"}
}"

I would like to convert it to a JSON array; So, I have tried JSON_encode() , but it returns the following string:

""{\"option1\"=>\"Color\",\"attribute1\"=>{0=>\"Black\", 1=>\"White\",2=>\"Blue\"},\"option2\"=>\"Size\",\"attribute2\"=>{0=>\"S\", 1=>\"L\",2=>\"M\"}}"" 

Could you please advise me on how to achieve what i want.

Thanks

The preferable way would be affecting the service which gives you such kind of strings to get a valid JSON string(if it's possible).
At the moment, if it's about adapting some "arbitrary" string to JSON notation format and further getting a JSON "array" use the following approach with preg_replace and json_decode functions:

$json_str = '{
      "option1"=>"Color",
      "attribute1"=>{0=>"Black", 1=>"White",2=>"Blue"},
      "option2"=>"Size",
      "attribute2"=>{0=>"S", 1=>"L",2=>"M"}
}';

// To get a 'pure' array
$arr = json_decode(preg_replace(["/\"?(\w+)\"?=>/", "/[\r\n]|\s{2,}/"], ['"$1":', ''], $json_str), true);
print_r($arr);

The output:

Array
(
    [option1] => Color
    [attribute1] => Array
        (
            [0] => Black
            [1] => White
            [2] => Blue
        )

    [option2] => Size
    [attribute2] => Array
        (
            [0] => S
            [1] => L
            [2] => M
        )
)

To get a JSON string representing an array:

$json_arr = json_encode($arr);
print_r($json_arr);

The output:

{"option1":"Color","attribute1":["Black","White","Blue"],"option2":"Size","attribute2":["S","L","M"]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM