开发者

how to fix a malformed JSON in php

i have this JSON string that i want to decode it with json_decode(); function

{"phase":2,"id":"pagelet_profile_picture","css":["VCxcl","Ix2pq"],"js":["fZYUE","VfnZ3"],"content":{"pagelet_profile_picture":"\u003cdiv class=\"profile-picture\">\u003cspan class=\"profile-picture-overlay\">\u003c\/span>\u003cimg class=\"photo img\" src\=\"http:\/\/profile.ak.fbcdn.net\/hprofile-ak-snc4\/222_111_2222_n.jpg\" alt=\"bla bla\" id=\"profile_pic\" \/>开发者_运维百科;\u003c\/div>"}}

there is the json_last_error(); but it not helping me. (got JSON_ERROR_STATE_MISMATCH and JSON_ERROR_SYNTAX sometimes)

i want to know what wrong with this JSON string and how i can fix it automatically in PHP so i can decode it. some code will be very helpful thanks.


Using a json lint, it seems the problem is the src\=

the \ escapes the = sign, which makes no sense.

If you replace src\= with src= it passes the validator.

The fix:

  1. Fix the code that generates the json string in the first place.

or

  1. use str_replace to change 'src\=' to 'src='


The problem with a wrong encoding is that it's just a wrong encoding. Things then break.

If the problem is related to invalid escape sequences as Ben pointed out in his answer, you can try to fix the input string for these sequences, probably with a smarter algorithm that is looking for any not-needed escape sequence replacing it with it's non-escaped value by removing the escape character \.

You can do so by creating a list of characters that need actual to be escaped, then parse the whole string for the escape character, if found, check if the next character requires escaping or not and then act upon.

However that's only one strategy and as the input is not properly encoded, it's not easy to just fix things because they are already broken.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜