Transform into json

Asked

Viewed 61 times

2

I have a string:

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

Basically I’m looking for a quick way to turn this into JSON, I mean, quote (") in each index (key), so that it becomes the valid JSON to then do json_decode()

2 answers

3


Although I don’t see the need to add " key, because you will be able to work with the object JSON likewise, here is a solution:

$json = '{name:"Sara", daypart:"day", href:"/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);

Exit:

"{\"name\":\"Sara\",\"daypart\":\"day\",\"href\":\"http:\/\/pt.stackoverflow.com\/questions\/ask\",\"bg\":\"su\",\"temp\":\"calor\",\"realfeel\":\"hot\",\"text\":\"cloudy\"}"
  • Could you explain to me what you’re doing at preg_replace sff, and why "" in output

  • comes from json_encode and not of preg_replace,

  • Without the preg_replace I can’t do this

  • @Miguel the preg_replace in this case serves to put the " in your keys

  • 1

    Yes but you said "Although I don’t see the need to add " in the key, because you’ll be able to work with the JSON object the same way...", but I’m seeing that without the preg_replace wouldn’t. Anyway it worked, thank you so much again

  • @Miguel using only the json_encode($json); didn’t work out?

  • @Kaduamaral the json_encode direct does not play " in the keys

  • Right, are you using the json that bind? If what ails you is the quotation marks, then Maicon’s answer is right for you. ;)

  • Yes you did, but without the preg_replace (quotation marks) I wouldn’t, I wouldn’t print anything. I’m using php

  • 1

    Maicon $json is what he wants, not the json_encode($json) (this last one gives the "jsonzada" version of a string, not an object). And personal, he wants the quotes in the key otherwise JSON is invalid. Format specification requires quotation marks, right @Miguel?

  • Exactly, I wanted it to stay JSON and then I could transform it into an array (json_decode()) (PHP) and work the data, which without the quotation marks would not work, would not be a valid JSON.

Show 6 more comments

1

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

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

This will convert your string and a JSON fully usable

  • No, you won’t, because JSON is invalid (key quotes are required). However, if this is sent straight from PHP to JS, it can be used with a literal object: var obj = {name:"Sara", daypart:"day", href:"http://answall.com/questions/ask", bg:"su", temp:"calor", realfeel:"hot", text:"cloudy"};.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.