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 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题