Why Is Json_Encode Adding Backslashes

Why is json_encode adding backslashes?

Can anyone tell me why json_encode adds slashes?

Forward slash characters can cause issues (when preceded by a < it triggers the SGML rules for "end of script element") when embedded in an HTML script element. They are escaped as a precaution.

Because when I try do use jQuery.parseJSON(response); in my js script, it returns null. So my guess it has something to do with the slashes.

It doesn't. In JSON "/" and "\/" are equivalent.

The JSON you list in the question is valid (you can test it with jsonlint). Your problem is likely to do with what happens to it between json_encode and parseJSON.

php json_encode() automatically added slashes before slashes

Why you do like this? Is totaly bad thing adding slashes manualy.

You can just generate JSON using arrays like:

$arr=array();

$arr['buttonText']="Large Button";
$arr['campName']="Large's Button Test";
$arr['buttonSize']=1;

echo json_encode($arr);

Just use json_encode() to store values and json_decode() to get values.

Here is diferent aproach:

$arr=array(
'buttonText'=>"Large Button",
'campName'=>"Large's Button Test",
'buttonSize'=>1,
);

echo json_encode($arr);

JSON ENCODE - Manual

JSON DECODE - Manual

json_encode() adding slashes automaticaly and json_decode() remove it. You don't need to think about that. Just don't worry and be happy.

How to remove backslash on json_encode() function?

json_encode($response, JSON_UNESCAPED_SLASHES);

PHP json_encode Problem with Backslash and Array Name

For the first point, if I try doing this :

$str = "this / string";
var_dump(json_encode($str));

I get :

string '"this \/ string"' (length=16)

With backslashes too.



Looking at json.org, it seems the JSON standard defines that slashes, inside strings, should be escaped.

So, json_encode() seems to be doing the right thing.

If you do not want those slashes to be escaped, then, you don't want valid-JSON, and should not work with json_encode.



For the second point, now, you should not use this :

$posts[] = array(..., $posts2 );

Instead, you should use :

$posts[] = array(..., 'attach' => $posts2 );

This way, that last element of the array will have the 'attach' name.

json_encode() escaping forward slashes

is there a way to disable it?

Yes, you only need to use the JSON_UNESCAPED_SLASHES flag (PHP 5.4+).

!important read before: https://stackoverflow.com/a/10210367/367456 (know what you're dealing with - know your enemy: DO NOT USE in web/html context - CLI, unless CGI, might be fine thought, if they think they need it in JSON HTTP context for readability purposes, they have a different problem)

json_encode($str, JSON_UNESCAPED_SLASHES);

If you don't have PHP 5.4 at hand (you certainly already asserted the warning above), pick one of the many existing functions and modify them to your needs, e.g. http://snippets.dzone.com/posts/show/7487 (archived copy).

Example Demo

<?php
/*
* Escaping the reverse-solidus character ("/", slash) is optional in JSON.
*
* This can be controlled with the JSON_UNESCAPED_SLASHES flag constant in PHP.
*
* @link http://stackoverflow.com/a/10210433/367456
*/

$url = 'http://www.example.com/';

echo json_encode($url), "\n";

echo json_encode($url, JSON_UNESCAPED_SLASHES), "\n";

Example Output:

"http:\/\/www.example.com\/"
"http://www.example.com/"

json_encode adding unwanted slashes

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"}}

How to deal with backslashes in json strings php

The answer is in the question:

$jsonEncodedString = json_encode($object);
echo $jsonEncodedString;
// Result of echo being:
// {"namespace":"myCompany\\package\\subpackage"}

You don't have to strip any slashes. On the contrary. You have to express the echo-ed text as PHP source code.

$yetAnotherObject = json_decode('{"namespace":"myCompany\\\\package\\\\subpackage"}');

The backslash (\) is a special character in both PHP and JSON. Both languages use it to escape special characters in strings and in order to represent a backslash correctly in strings you have to prepend another backslash to it, both in PHP and JSON.

Let's try to do the job of the PHP parser on the string above. After the open parenthesis it encounters a string enclosed in single quotes. There are two special characters that needs escaping in single quote strings: the apostrophe (') and the backslash (\). While the apostrophe always needs escaping, the PHP interpreter is forgiving and allows unescaped backslashes as long as they do not create confusion. However, the correct representation of the backslash inside single quoted strings is \\.

The string passed to function json_decode() is

{"namespace":"myCompany\\package\\subpackage"}

Please note that this is the exact list of characters processed on runtime and not a string represented in PHP or any other language. The languages have special rules for representing special characters. This is just plain text.

The text above is interpreted by function json_decode() that expects it to be a piece of JSON. JSON is a small language, it has special rules for encoding of special characters in strings. The backslash is one of these characters and when it appears in a string it must be prepended by another backslash. JSON is not forgiving; when it encounters a backslash it always treats it as an escape character for the next character in the string.

The object created by json_decode() after successful parsing of the JSON representation you pass them contains a single property named namespace whose value is:

myCompany\package\subpackage

Note again that this is the actual string of characters and not a representation in any language.

What went wrong?

Back to your code:

$yetAnotherObject = json_decode('{"namespace":"myCompany\\package\\subpackage"}');

The PHP parser interprets the code above using the PHP rules. It understands that the json_decode() function must be invoked with the text {"namespace":"myCompany\package\subpackage"} as argument.

json_decode() uses its rules and tries to interpret the text above as a piece of JSON representation. The quote (") before myCompany tells it that "myCompany\package\subpackage" must be parsed as string. The backslash before package is interpreted as an escape character for p but \p is not a valid escape sequence for strings in JSON. This is why it refuses to continue and returns NULL.



Related Topics



Leave a reply



Submit