dongyi7513 2016-03-28 17:57 采纳率: 100%
浏览 13

无法解析看起来完全相同的两个json字符串之一

I used JSON.stringify to convert a JSON object to string, stored it in a database and retrieved it. When I am trying to decode it into json using json_decode(), it is returning NULL(I used var_dump() to verify it).

{"profilediv":" klsadnlksa ","profilediv2":" sankldnlkas ","profilediv3":" nsjakdnsjka "}

{"profilediv":"nsjakdnsjka","profilediv2":"sankldnlkas","profilediv3":"klsadnlksa"}

I am able to parse the second string, but not the first one. Here the entire code.

  <?php
$x = '{"profilediv":"

klsadnlksa

","profilediv2":"

sankldnlkas

","profilediv3":"

nsjakdnsjka

"}';
$x = trim($x);
$y = json_decode($x,true);
var_dump($y);
$json = '{"profilediv":"nsjakdnsjka","profilediv2":"sankldnlkas","profilediv3":"klsadnlksa"}';
var_dump(json_decode($json));
?>

And here is the output

NULL object(stdClass)#1 (3) { ["profilediv"]=> string(11) "nsjakdnsjka" ["profilediv2"]=> string(11) "sankldnlkas" ["profilediv3"]=> string(10) "klsadnlksa" }

I am able to parse $json but not $x. Any help is appreciated.Thanks in advance.

  • 写回答

2条回答 默认 最新

  • du1462 2016-03-28 18:04
    关注

    Add this to remove new-lines

    $x = str_replace("
    ",'',$x);
    $y = json_decode($x,true);
    

    Will be var_dumped as:

    Array
    (
        [profilediv] => klsadnlksa
        [profilediv2] => sankldnlkas
        [profilediv3] => nsjakdnsjka
    )
    

    trim — Strip whitespace (or other characters) from the beginning and end of a string

    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用