Transform into json

2

I have a string:

{name:"Sara", daypart:"day", href:"http://pt.stackoverflow.com/questions/ask", bg:"su", temp:"calor", realfeel:"hot", text:"cloudy"}

I'm basically looking for a quick way to turn this into JSON, ie put quotation marks ( " ) on each index (key), so that it becomes valid JSON and then make json_decode()

    
asked by anonymous 30.06.2015 / 18:58

2 answers

3

Although I do not see the need to add " to the key, because you will be able to work with the object JSON in the same way, here is a solution:

$json = '{name:"Sara", daypart:"day", href:"http://pt.stackoverflow.com/questions/ask", bg:"su", temp:"calor", realfeel:"hot", text:"cloudy"}';

$json = preg_replace('/([{,])(\s*)([A-Za-z0-9_\-]+?)\s*:/','$1"$3":',$json);    
echo json_encode($json);

Output:

"{\"name\":\"Sara\",\"daypart\":\"day\",\"href\":\"http:\/\/pt.stackoverflow.com\/questions\/ask\",\"bg\":\"su\",\"temp\":\"calor\",\"realfeel\":\"hot\",\"text\":\"cloudy\"}"
    
30.06.2015 / 19:10
1

You can use javascript to do this using JSON.parse()

JSON.parse('{name:"Sara", daypart:"day", href:"http://pt.stackoverflow.com/questions/ask", bg:"su", temp:"calor", realfeel:"hot", text:"cloudy"}');

This will convert your string and a JSON fully usable

    
30.06.2015 / 19:16