Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

Invalid JSON parsing using PHP

I'm pulling a JSON feed that is invalid JSON. It's missing quotes entirely. I've tried a few things, like explode() and str_replace(), to get the string looking a little bit more like valid JSON, but with an associate JSON string inside, it generally gets screwed up.

Here's an example:

id:43015,name:'John Doe',level:15,systems:[{t:6,glr:1242,n:'server',s:185,c:9}],classs:0,subclass:5

Are there any JSON parsers for php out there that can handle invalid JSON like this?

Edit: I'm trying to use json_decode() on this string. It returns nothing.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. All the quotes should be double quotes " and not single quotes '.
  2. All the keys should be quoted.
  3. The whole element should be an object.
    function my_json_decode($s) {
        $s = str_replace(
            array('"',  "'"),
            array('"', '"'),
            $s
        );
        $s = preg_replace('/(w+):/i', '"1":', $s);
        return json_decode(sprintf('{%s}', $s));
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...