How to deal with backslashes in json strings php

how to remove backslash from json object in android
how to remove backslash from json object in java
php remove backslash from string
backslashes in json python
remove backslash from json php
json adding backslash automatically
remove backslash from json python
php escape forward slash

There appears to be an oddity with json_encode and/or json_decode when attempting decode a string that was produced by json_encode:

    $object = new stdClass;
    $object->namespace = 'myCompany\package\subpackage';

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

    $anotherObject = json_decode($jsonEncodedString);
    echo $anotherObject->namespace;
    // Result of echo being:
    // myCompany\package\subpackage


    $yetAnotherObject = json_decode('{"namespace":"myCompany\\package\\subpackage"}');
    // Result should be:
    // myCompany\package\subpackage
    // But returns an invalid string sequence error instead...
    echo json_last_error_msg();

I've never experienced a problem previous to this, as I've never had to capture a string with backslashes in it until today. In reviewing the code above, I can encode/decode utilizing PHP's built in components. However if I attempt to decode a string that was produced by this encoder I get an error message. I've read in documentation items like "Predefined Constants" and other stack questions like "how remove the backslash ("\") in the json response using php?". But I can't seem to find a reason WHY I can't decode a string that was produced by json_encode. The PHP version I'm using to test this code is 5.5.9.

I know I could be totally clueless by missing something, but should I be handling my string that was produced by json_encode differently if I attempt to use it elsewhere?

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.

stripslashes - Manual, The addslashes() function returns a string with backslashes in front of predefined characters. The predefined characters are: single quote ('); double quote (")� Since PHP 5.4 there are constants which can be used by json_encode() to format the json reponse how you want. To remove backslashes use: JSON_UNESCAPED_SLASHES . Like so:

You will need to encode your double backslashes \\ into quadruple backslashes \\\\ because php interprets a backslash as an escape character in single and double quoted strings. This means that \\ is seen as \.

This example illustrates what is happening

<?php
$str = '{"namespace":"myCompany\\package\\subpackage"}';
echo $str, PHP_EOL; // \\ seen as \
$yetAnotherObject = json_decode($str);
echo json_last_error_msg(), PHP_EOL;

var_dump(json_decode(str_replace('\\', '\\\\', $str)));
echo json_last_error_msg(), PHP_EOL;

This is the output

$ php test.php
{"namespace":"myCompany\package\subpackage"}
Syntax error
class stdClass#1 (1) {
  public $namespace =>
  string(28) "myCompany\\package\\subpackage"
}
No error

PHP addslashes() Function, Converting JSON object to String will escape the forward slash. are available, whether ESQL syntax is case sensitive, and how to handle comments. Newton Internet-Draft ARIN Intended status: Standards Track P. PHP escapes forward� Decoding JSON data using PHP. You can parse or read JSON data from JSON object or any JSON file using PHP json_decode() method. Different examples of parsing JSON data using PHP are given below. Example-1: In the following example, JSON data is assigned in a variable and PHP json_decode() method is used to read the data in PHP format.

Thats because PHP is converting the double slashes into a single slash before passing it to json_decode. You will need to either escape the double slashes (a pain I know) or construct the object manually.

http://php.net/manual/en/language.types.string.php#language.types.string.syntax.single

Json Stringify Escape Forward Slash, I've created a json object which I'm adding value like json.put(key, value). http:// stackoverflow.com/questions/21036626/remove-backslashes-from-json-data-in- Java tried to escape your string as " " is part of your string not actual quotes� The value of any JSON key can be a string, Boolean, number, null, array, or object. Comments are not allowed in JSON. Although JSON resembles an object or an array, JSON is a string. A serialized string, which means it can later be parsed and decoded into data types. Using data from JSON with PHP

Please use the PHP native function stripslashes

https://www.php.net/manual/en/function.stripslashes.php

<?php
$str = 'myCompany\\package\\subpackage';
echo stripslashes(json_encode($str));
//output: myCompany\package\subpackage

Solved: Remove backslash from Json Object, slashes in json response php stripslashes in javascript how to remove backslash from json data in php PHP stripslashes() Function, Un-quotes a quoted string. when you assign the json value then its better to solve it at the begining rather � I am trying to remove all backslashes from a url-decoded string, but it is outputting \ rather than outputting the url-decoded string with \ removed. Please can you tell me my problem.

You can just use the stripslashes function to strip the dashes and it will work tested

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

how to remove back slashes from json output in php, remove slash from string javascript remove backslash from json php for me: result = result.replace("\\", result) Do I need to treat result as a raw string? json = JSON.stringfy(json); the detail here is that I’m using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes.

how remove the backslash ("\") in the json response using php?, Hi all,I've been running some tests with retrieving string data (of data type Text JSON result of replace pipe is : "test with literal backslash \" Not sure if you could solve your issue entirely with this, but it may help you ;). This is usually because the server side code didn't properly create the JSON. That's why you see the \" inside the string. This lets the parser know that " is to be treated literally and doesn't terminate the string. So you can either fix the server side code, so that you don't double encode the data, or you have to decode the JSON twice, e.g.

How to escape/encode literal backslashes when retrieved as JSON , You can't: the backslashes are added to prevent the double quote characters that follow them being interpreted as double quotes which� json = JSON.stringfy(json); the detail here is that I'm using blade inside laravel to build a three view form, so I can go back and forward, I have in between every back and forward button validations and when I go back in the form without reloading the page my json get filled by backslashes.

How to avoid back slash characters from json string in C , Swift String escaping when serializing to JSON using Codable , I ended up using I'm having to deal with a third-party API that sends a escaped string instead of a JSON Home � Php � How to remove backslash on json_encode() function? This is new behavior - see the result in PHP 5.2.4 : php > var_dump(json_decode('this is a simple string')); string(23) "this is a simple string" in PHP 5.3.2 : php > var_dump(json_decode('this is a simple string')); NULL I had several functions that relied on checking the value of a purported JSON string if it didn't decode into an object/array.

Comments
  • what if I want to use the json_encode from PHP directly in javascript, like JSON.parse('$encoded') then it will not work.
  • The string generated by json_encode() is a perfectly valid JavaScript data definition. A fragment (of HTML+PHP) like this: let x = <?php json_encode($value); ?>; generates a correct fragment of JavaScript. There isn't anything to decode.
  • if you insist on it, take this JSON that is generated by json_encode of an entity in the database. {"id":20,"user_id":83,"done_at":null,"created_at":"2020-05-18 23:26:21","updated_at":"2020-05-18 23:26:21","taskable_type":"App\\Entities\\Tasks\\NormalTask","taskable_id":1,"counter":0} try to parse that using javascript, it will not work because it has a namespace that json_encode has escaped, but JSON is not seeing it as escaped!
  • It is perfectly valid JSON and it can be used directly as JavaScript code. Do not wrap a JSON in quotes or apostrophes! It does not make it a valid JavaScript string. Use it as is. If you want to parse it using JSON.parse() then write it into a file then read it from there.
  • that was awesome, it works for me! but I was thinking that I always need to parse data from PHP to convert it to JS object, can you please illustrate more, if no need to parse the data then what is the use of JSON.parse?
  • So to be clear, the suggestion is to do something like: a str_replace() on the string and add an additional backslash to the string that I am attempting to json_decode? Seems kinda janky.
  • Yeah, its a weird workaround, buts its the easiest way to do it. str_replace( "\\", "\\\\", $input );
  • This really seems odd, because now after I sanitize my input I now have to check each and every string for backslashes and do a replace. It seems like this shouldn't be something that should be handled at the programming level but at the language level. Well I learned something today, thanks Blake!
  • PHP doesn't convert anything. You mistake the conventions used by a language to represent special characters in a string with the sequence of characters produced by the parser on the runtime by following the conventions. \` is the way to tell the PHP parser you want a ` in the string.
  • If you stripslashes(), then you are changing the data within the object to : {"namespace":"myCompanypackagesubpackage"} which is a different value.
  • As from docs: "Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\) are made into a single backslash ()." so in this case it would only strip one of the two slashes, which however is not the expected result.