Ben
Ben

Reputation: 249

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.

Upvotes: 1

Views: 7530

Answers (2)

hakre
hakre

Reputation: 197692

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.

Upvotes: 1

Ben
Ben

Reputation: 21249

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='

Upvotes: 2

Related Questions