简体   繁体   English

将PHP字符串转换为JSON数组(键:值)

[英]Convert PHP string to JSON array(key:value)

I have the following string that I receive from an API call: 我从API调用中收到以下字符串:

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; 我想将其转换为JSON数组; So, I have tried JSON_encode() , but it returns the following string: 因此,我尝试了JSON_encode() ,但是它返回以下字符串:

""{\"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). 最好的方法是影响服务,该服务为您提供这种字符串以获取有效的JSON字符串(如果可能)。
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表示法格式并进一步获得JSON“数组”,请使用以下方法与preg_replacejson_decode函数:

$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字符串,请执行以下操作:

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

The output: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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