2

I have an API service with an web based sms provider when I call to api a m getting the below response

{Promotional SMS Credits: 0, Transactional SMS Credits: 9972}

I tried json_decode() to convert it array but failed due to non valid JSON format (missed Quotes for key and value)

I want convert a non valid json string to a valid JSON in PHP like below

{"Promotional SMS Credits": "0", "Transactional SMS Credits": "9972"}

can any one help me?

1
  • Well why are you having the invalid JSON to begin with, that really is the issue. Commented Aug 10, 2015 at 8:12

4 Answers 4

1

Contact the company that run the API feed and tell them that the JSON is wrong...

you can do a search and replace (preg_replace), but the hard part is going to be creating your fuzzy matching rules, because in order to parse it, you will need to assume some things. Probably, you will need to assume either:

1a) Keys don't contain colons 1b) or key quotes are properly escaped and 2a) Values don't contain commas 2b) or values have properly escaped quotes.

Sign up to request clarification or add additional context in comments.

Comments

0

Quite a crude function but it does return a json formatted version of the original string.

        $str='{Promotional SMS Credits: 0, Transactional SMS Credits: 9972}';

        function bad_str_to_json($str){
            $str=str_replace(array('{','}'),'',$str);
            $pairs=explode(',',$str);
            $json=array();
            foreach($pairs as $pair){
                list($p,$v)=explode(':',$pair);
                $json[trim($p)]=trim($v);
            }
            return json_encode($json);
        }

        echo bad_str_to_json($str);

1 Comment

any possible solution using preg_replace() function ?
0

Hope this will help you. If you have invalid JSON you can convert using below code:

    $invalidJson = '{
    Promotional SMS Credits: "0",
    Transactional SMS Credits: "9972"
}';
$ValidJson = preg_replace("/\s{1,}/", ":", $invalidJson);

2 Comments

not working, my required format is {"Promotional SMS Credits": "0", "Transactional SMS Credits": "9972"}
Really not working i tried below $invalidJson = '{Promotional SMS Credits: 0, Transactional SMS Credits: 9972}'; $ValidJson = preg_replace("/(\n[\t ]*)([^\t ]+):/", "$1\"$2\":", $invalidJson);
0
$str='{Promotional SMS Credits: 0, Transactional SMS Credits: 9972}';
$str=str_replace(array('{','}'),'',$str);
$tmp=explode(',',$str);
$res=array();
foreach($tmp as $t){
    $tmp2=explode(':',$t);
    $tmp2=array_combine((array)$tmp2[0],(array)$tmp2[1]);
    $res=array_merge($res,$tmp2);

}
echo json_encode($res,false);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.