What is wrong with this JSON string? - json

I keep getting NULL when i do $data = json_decode($data); . To encode it in JS I use var data = JSON.stringify( my_obj ); What is wrong with this JSON string?
'guide' => string (1583) "[{\"instructions\":[\"sdasda\"],\"media\":[{\"id\":95,\"titl …"
EDIT:
I am adding the entire string as requested:
[{\"instructions\":[\"sdasda\"],\"media\":[{\"id\":95,\"title\":\"item4_1444\",\"filename\":\"item4_1444.jpg\",\"url\":\"http://localhost:8888/sandbox/content/uploads/2014/08/item4_1444.jpg\",\"link\":\"http://localhost:8888/sandbox/example/change-phone-home-button/item4_1444/\",\"alt\":\"\",\"author\":\"1\",\"description\":\"\",\"caption\":\"\",\"name\":\"item4_1444\",\"status\":\"inherit\",\"uploadedTo\":86,\"date\":\"2014-08-24T16:39:15.000Z\",\"modified\":\"2014-08-24T16:39:15.000Z\",\"menuOrder\":0,\"mime\":\"image/jpeg\",\"type\":\"image\",\"subtype\":\"jpeg\",\"icon\":\"http://localhost:8888/sandbox/includes/images/media/default.png\",\"dateFormatted\":\"24/08/2014\",\"nonces\":{\"update\":\"46bbaaed37\",\"delete\":\"bcda3390c5\",\"edit\":\"ea35506ec2\"},\"editLink\":\"http://localhost:8888/sandbox/admin/post.php?post=95&action=edit\",\"sizes\":{\"thumbnail\":{\"height\":150,\"width\":150,\"url\":\"http://localhost:8888/sandbox/content/uploads/2014/08/item4_1444-150x150.jpg\",\"orientation\":\"landscape\"},\"medium\":{\"height\":300,\"width\":200,\"url\":\"http://localhost:8888/sandbox/content/uploads/2014/08/item4_1444-200x300.jpg\",\"orientation\":\"portrait\"},\"full\":{\"url\":\"http://localhost:8888/sandbox/content/uploads/2014/08/item4_1444.jpg\",\"height\":960,\"width\":640,\"orientation\":\"portrait\"}},\"height\":960,\"width\":640,\"orientation\":\"portrait\",\"compat\":{\"item\":\"\",\"meta\":\"\"},\"html_id\":\"ge-step-image-1\"}]}]

There is nothing wrong with the JSON other than the fact that the double-quotes that are supposed to delimit string values in the JSON have been encoded as if they were double-quotes within a JSON string.
For example:
\"instructions\":
Should be simply:
"instructions":
To illustrate how double-quote escaping is intended to work in JSON, consider encoding an object with a single item named height with the string value 6'2":
height: 6'2"
Encoded in JSON this would be:
{ "height": "6'2\"" }
The JSON strings are delimited with double-quotes. The double-quote internal to the string value itself is then escaped using the backslash character.
Supplementary to this of course is how you encode your string for your given source code language.
If you are using a literal string in your source which is itself double-quote delimited or places special interpretation on '\' then you must adopt the conventions required by the source language in encoding your literals.
Again, by way of an example, consider how the above string would be represented in two different languages:
// C#
s = "{ \"height\": \"6'2\\\"\" }";
// Delphi
s := '{ "height": "6''2\"" }';
In C# since '\' marks an escaped character then the '\' in the JSON must itself be escaped. The double quote characters also need to be escaped since C# string literals are also double-quote delimited.
In Delphi, string literals are single quote delimited, so there is no need to escape the double-quotes, but the single-quote within the string must be. In Delphi this involves only doubling the single quote sequence and there is no need to escape the '\' or '"' characters at all.
Hopefully this will help you understand any mistakes that you may be making in the representation of your JSON strings.

Related

Strip backslashes from encoded JSON response

Building a Json respose with erlang. First I construct the data in terms and then use jsx to convert it to JSON:
Response = jsx:term_to_json(MealsListResponse),
The response actually is valid JSON according to the validators I have used:
The problem is when parsing the response in the front end. Is there a way to strip the backslashes from the Erlang side, so that the will not appear on the payload response?
The backslashes are not actually part of the string. They're just used when the string is printed as a term - that is, in the same way you'd write it in an Erlang source file. This works in the same way as character escapes in strings in C and similar languages: inside double quotes, double quotes that should be part of the string need to be escaped with backslashes, but the backslashes don't actually make it into the string.
To print the string without character escapes, you can use the ~s directive of io:format:
io:format("~s~n", [Response]).
If you're sending the response over a TCP socket, all you need to do is converting the string to binary with an appropriate Unicode conversion. Most of the time you'll want UTF-8, which you can get with:
gen_tcp:send(MySocket, unicode:characters_to_binary(Response)).

How to I escape [] square brackets when deserializing Json objects

I have a value from a result set example [22 mm]. This is the literal value of the string and not an array. The deserialiser NewtonSoft one complains as it think its an array. How do I escape these square brackets? and deserialise it to a value [22 mm] which is the literal value
If you serialize an object, or set the value on a JObject, the string will be escaped automatically.
However, the character [ will never need to be escaped when in a string, simply because it will always be surrounded by strings delimitors : ".
If your Json parser thinks it's an array, it's probably because you didn't surround your value with double quotes. Add the double quotes to indicate you're dealing with strings and you should be all good.

How to escape backslash in json object key

I want to reference this json key : Added Date/Time
{{ contact.["Added Date\\Time"] }}
Why isn't this working?
If you want to include a literal double quote in a JSON string, you must escape it by preceding it with a backslash . So your JSON string would have to look like this:
{"key" : " \"Some text WITH quotes\" "}
See json.org for the official JSON syntax.
The forward slash / is not a special character and does not need to be escaped. The backslash \ needs to be escaped with itself: \\.
Because the string literal does not match the required key. You need to ensure that the string literal in your source code matches the actual JSON key.
In most languages, this character sequence will do it: Added Date/Time. (there is no escaping required).
Note, this string is NOT a JSON string - it's a string literal in your programming language. Thus, this string must obey the escaping rules of your current programming language, not the rules of JSON.

How to escape special characters in building a JSON string?

Here is my string
{
'user': {
'name': 'abc',
'fx': {
'message': {
'color': 'red'
},
'user': {
'color': 'blue'
}
}
},
'timestamp': '2013-10-04T08: 10: 41+0100',
'message': 'I'mABC..',
'nanotime': '19993363098581330'
}
Here the message contains single quotation mark, which is same as the quotation used in JSON. What I do is fill up a string from user inputs such as message. So, I need to escape those kind of special scenarios which breaks the code. But other than string replace, is there any way to make them escape but still allow HTML to process them back to the correct message?
I'm appalled by the presence of highly-upvoted misinformation on such a highly-viewed question about a basic topic.
JSON strings cannot be quoted with single quotes. The various versions of the spec (the original by Douglas Crockford, the ECMA version, and the IETF version) all state that strings must be quoted with double quotes. This is not a theoretical issue, nor a matter of opinion as the accepted answer currently suggests; any JSON parser in the real world will error out if you try to have it parse a single-quoted string.
Crockford's and ECMA's version even display the definition of a string using a pretty picture, which should make the point unambiguously clear:
The pretty picture also lists all of the legitimate escape sequences within a JSON string:
\"
\\
\/
\b
\f
\n
\r
\t
\u followed by four-hex-digits
Note that, contrary to the nonsense in some other answers here, \' is never a valid escape sequence in a JSON string. It doesn't need to be, because JSON strings are always double-quoted.
Finally, you shouldn't normally have to think about escaping characters yourself when programatically generating JSON (though of course you will when manually editing, say, a JSON-based config file). Instead, form the data structure you want to encode using whatever native map, array, string, number, boolean, and null types your language has, and then encode it to JSON with a JSON-encoding function. Such a function is probably built into whatever language you're using, like JavaScript's JSON.stringify, PHP's json_encode, or Python's json.dumps. If you're using a language that doesn't have such functionality built in, you can probably find a JSON parsing and encoding library to use. If you simply use language or library functions to convert things to and from JSON, you'll never even need to know JSON's escaping rules. This is what the misguided question asker here ought to have done.
A JSON string must be double-quoted, according to the specs, so you don't need to escape '.
If you have to use special character in your JSON string, you can escape it using \ character.
See this list of special character used in JSON :
\b Backspace (ascii code 08)
\f Form feed (ascii code 0C)
\n New line
\r Carriage return
\t Tab
\" Double quote
\\ Backslash character
However, even if it is totally contrary to the spec, the author could use \'.
This is bad because :
It IS contrary to the specs
It is no-longer JSON valid string
But it works, as you want it or not.
For new readers, always use a double quotes for your json strings.
Everyone is talking about how to escape ' in a '-quoted string literal. There's a much bigger issue here: single-quoted string literals aren't valid JSON. JSON is based on JavaScript, but it's not the same thing. If you're writing an object literal inside JavaScript code, fine; if you actually need JSON, you need to use ".
With double-quoted strings, you won't need to escape the '. (And if you did want a literal " in the string, you'd use \".)
Most of these answers either does not answer the question or is unnecessarily long in the explanation.
OK so JSON only uses double quotation marks, we get that!
I was trying to use JQuery AJAX to post JSON data to server and then later return that same information.
The best solution to the posted question I found was to use:
var d = {
name: 'whatever',
address: 'whatever',
DOB: '01/01/2001'
}
$.ajax({
type: "POST",
url: 'some/url',
dataType: 'json',
data: JSON.stringify(d),
...
}
This will escape the characters for you.
This was also suggested by Mark Amery, Great answer BTW
Hope this helps someone.
May be i am too late to the party but this will parse/escape single quote (don't want to get into a battle on parse vs escape)..
JSON.parse("\"'\"")
The answer the direct question:
To be safe, replace the required character with \u+4-digit-hex-value
Example:
If you want to escape the apostrophe ' replace with \u0027
D'Amico becomes D\u0027Amico
NICE REFERENCE:
http://es5.github.io/x7.html#x7.8.4
https://mathiasbynens.be/notes/javascript-escapes
Using template literals...
var json = `{"1440167924916":{"id":1440167924916,"type":"text","content":"It's a test!"}}`;
Use encodeURIComponent() to encode the string.
Eg.:
var product_list = encodeURIComponent(JSON.stringify(product_list));
You don't need to decode it since the web server automatically do the same.
To allow single quotes within doubule quoted string for the purpose of json, you double the single quote. {"X": "What's the question"} ==> {"X": "What''s the question"}
https://codereview.stackexchange.com/questions/69266/json-conversion-to-single-quotes
The \' sequence is invalid.
regarding AlexB's post:
\' Apostrophe or single quote
\" Double quote
escaping single quotes is only valid in single quoted json strings
escaping double quotes is only valid in double quoted json strings
example:
'Bart\'s car' -> valid
'Bart says \"Hi\"' -> invalid

Problem with decode UTF character from JSON data

I post data from user and then convert to JSON data and store in database.
To avoid problem with escape char, I used
$jsonData = json_encode($array_json_data,JSON_HEX_APOS|JSON_HEX_QUOT);
and it converted escaped char to UXXXX char.
Now I am having problem while decoding these data.
For example how can I print quote from U0027.
use html_entity_decode to convert quotes to its actual string representation