json_decode + json_encode combo没有创建原始JSON

时间:2012-03-19 07:51:52

标签: php json

我有一些通过API调用获得的JSON,我在其上运行json_decode,从中获取一个数组,然后使用json_encode对其进行重新编码。然而结果是不一样的JSON;它弄乱了网址。如何正确编码?

原始

{"created_at":"Mon, 19 Mar 2012 01:34:41 +0000","entities":{"hashtags":[{"text":"stanford","indices":[23,32]}],"urls":[{"url":"http:\/\/t.co\/Of4z6jKG","expanded_url":"http:\/\/360.io\/5sZc2T","display_url":"360.io\/5sZc2T","indices":[33,53]}],"user_mentions":[]},"from_user":"rayfk","from_user_id":335143881,"from_user_id_str":"335143881","from_user_name":"Raymond Kennedy","geo":{"coordinates":[37.4227,-122.1753],"type":"Point"},"id":181554251733020673,"id_str":"181554251733020673","iso_language_code":"en","metadata":{"result_type":"recent"},"profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","source":"<a href="http:\/\/www.occipital.com\/360\/app" rel="nofollow">360 Panorama<\/a>","text":"View from mid lake log #stanford http:\/\/t.co\/Of4z6jKG","to_user":null,"to_user_id":null,"to_user_id_str":null,"to_user_name":null}
解码/编码组合后

{"created_at":"Mon, 19 Mar 2012 01:34:41 +0000","entities":{"hashtags":[{"text":"stanford","indices":[23,32]}],"urls":[{"url":"http:\/\/t.co\/Of4z6jKG","expanded_url":"http:\/\/360.io\/5sZc2T","display_url":"360.io\/5sZc2T","indices":[33,53]}],"user_mentions":[]},"from_user":"rayfk","from_user_id":335143881,"from_user_id_str":"335143881","from_user_name":"Raymond Kennedy","geo":{"coordinates":[37.4227,-122.1753],"type":"Point"},"id":181554251733020673,"id_str":"181554251733020673","iso_language_code":"en","metadata":{"result_type":"recent"},"profile_image_url":"http:\/\/a0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","profile_image_url_https":"https:\/\/si0.twimg.com\/profile_images\/1468102095\/image_normal.jpg","source":"<a href="http:\/\/www.occipital.com\/360\/app" rel="nofollow">360 Panorama<\/a>","text":"View from mid lake log #stanford http:\/\/t.co\/Of4z6jKG","to_user":null,"to_user_id":null,"to_user_id_str":null,"to_user_name":null}

这些是完整的片段,但罪魁祸首是:

原始 "source":"&lt;a href=&quot;http:\/\/www.occipital.com\/360\/app&quot; rel=&quot;nofollow&quot;&gt;360 Panorama&lt;\/a&gt;"

"source":"<a href="http:\/\/www.occipital.com\/360\/app" rel="nofollow">360 Panorama<\/a>"

之后

2 个答案:

答案 0 :(得分:0)

我不确定是什么导致它,但您可以通过将html_entity_decode()函数应用于版本之后的来更正它。这会将&lt;&quot;之类的内容更改为原始格式。

根据它如何影响您的报价,您可以传递一些标记以获得所需的结果。

  • ENT_COMPAT:将转换双引号并单独留下单引号。
  • ENT_QUOTES:将同时转换双引号和单引号。
  • ENT_NOQUOTES:将双引号和单引号保留为未转换。

<强> [编辑]

通过此功能运行您的破解JSON:

function fixDoubleQuotedJSON($broken_json)
{
   return str_replace('"','\\"',$broken_json);
}

答案 1 :(得分:0)

http://codepad.org/DMkAS2iR

他们似乎是平等的,除了在一个不知名的地方:

before: "id":181554251733020673,"id_str"
after:  "id":181554251733020000,"id_str"

在“无损”json转换后,这些id不会真正匹配,PHP 5.4支持JSON_BIGINT_AS_STRING选项。

顺便说一句,Codepad的php版本是5.2.5;