Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

json_encode adding unwanted slashes

I have a json string saved in my db. When i retrieve it from db to pass it to the javascript function (ajax call) , along with the id of that row, i am json_encoding both (the query result array) and passing it to js. but json_encode is adding unwanted slashes to my already json string. how to escape it. remember i have to pass the id also as second element in array.

my json string in db is like:

{"field":"City","term":"Hawaiian Gardens, CA"}

and the id is say 5.

so the query result array in PHP is:

$savedVal['id'] = 5 
$savedVal['object_str'] = {"field":"City","term":"Hawaiian Gardens, CA"}

so after json_encode($savedVal) ideally it should be:

{"id":"5","object_str":{"field":"City","term":"Hawaiian Gardens, CA"}}

but json_encoding the array gives me:

{"id":"5","object_str":"{\"field\":\"City\",\"term\":\"Hawaiian Gardens, CA\"}}

extra slashes and quotes too around object_str value. Please help me.

Thank you.

like image 634
Prashant Avatar asked Mar 11 '10 14:03

Prashant


People also ask

Why are there slashes in my JSON file?

Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON. parse to parse that JSON string into a JSON object.

How remove slashes from JSON encode in PHP?

The stripslashes() function removes backslashes added by the addslashes() function. Tip: This function can be used to clean up data retrieved from a database or from an HTML form.

What is the difference between json_encode and Json_decode?

I think json_encode makes sure that php can read the . json file but you have to specify a variable name, whereas with json_decode it's the same but you have to specify a file name.


1 Answers

You are running JSON_encode on JSON - this is why the double escaping occurs. Try this:

$savedVal['id'] = 5 ;
$savedVal['object_str'] = json_decode( '{"field":"City","term":"Hawaiian Gardens, CA"}' );

echo json_encode( $savedVal );

Output

{"id":5,"object_str":{"field":"City","term":"Hawaiian Gardens, CA"}}
like image 200
Andy Avatar answered Sep 16 '22 20:09

Andy