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?

Bhavin Bhadani
  • 22,224
  • 10
  • 78
  • 108
Kishore Reddy
  • 147
  • 10

4 Answers4

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.

Community
  • 1
  • 1
Ilanus
  • 6,690
  • 5
  • 13
  • 37
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);
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
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);
Vishal Bharti
  • 185
  • 1
  • 9
  • not working, my required format is {"Promotional SMS Credits": "0", "Transactional SMS Credits": "9972"} – Kishore Reddy Aug 10 '15 at 08:36
  • Really not working i tried below $invalidJson = '{Promotional SMS Credits: 0, Transactional SMS Credits: 9972}'; $ValidJson = preg_replace("/(\n[\t ]*)([^\t ]+):/", "$1\"$2\":", $invalidJson); – Kishore Reddy Aug 10 '15 at 08:41
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);
Rajeev Ranjan
  • 4,152
  • 3
  • 28
  • 41