douju9272 2017-01-09 08:18
浏览 270
已采纳

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

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

  • 写回答

1条回答 默认 最新

  • doushe7934 2017-01-09 08:46
    关注

    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+)\"?=>/", "/[
    ]|\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"]}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?