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

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.

Related

Fixind invalid json in SQL

I'm parsing json in redshift using json_extract_path_text, but this json is invalid (one of the fields contains double quote inside of the string value):
"somefield": "4 *\\"`)(z"
Is there any way to get rid of this quote and replace it with some other value (I do not really care about this particular data as it is wrong anyway, but I want to fetch some other parts of this json).
It looks like you have the wrong number of backslashes in the string. You need either or 1, to just get the double quotes, or 3 to get a backslash and the double quote. But this isn't really the question.
You can use the REPLACE() function to strip the \" text out. https://docs.aws.amazon.com/redshift/latest/dg/r_REPLACE.html
REPLACE(json_text, '\\"', '')
I believe REPLACE() doesn't do any string interpretation so no additional escaping will be needed.

Interpolating a JSON string removes JSON quotations

I have the following two lines of code:
json_str = _cases.to_json
path += " #{USER} #{PASS} #{json_str}"
When I use the debugger, I noticed that json_str appears to be formatted as JSON:
"[["FMCE","Wiltone","Wiltone","04/10/2018","Marriage + - DOM"]]"
However, when I interpolate it into another string, the quotes are removed:
"node superuser 123456 [["FMCE","Wiltone","Wiltone","04/10/2018","Marriage + - DOM"]]"
Why does string interpolation remove the quotes from JSON string and how can I resolve this?
I did find one solution to the problem, which was manually escaping the string:
json_str = _cases.to_json.gsub('"','\"')
path += " #{USER} #{PASS} \"#{json_str}\""
So basically I escape the double quotes generated in the to_json call. Then I manually add two escaped quotes around the interpolated variable. This will produce a desired result:
node superuser 123456 "[[\"FMCE\",\"Wiltone\",\"Wiltone\",\"04/10/2018\",\"Marriage + - DOM\"]]"
Notice how the outer quotes around the collection are not escaped, but the strings inside the collection are escaped. That will enable JavaScript to parse it with JSON.parse.
It is important to note that in this part:
json_str = _cases.to_json.gsub('"','\"')
it is adding a LITERAL backslash. Not an escape sequence.
But in this part:
path += " #{USER} #{PASS} \"#{json_str}\""
The \" wrapping the interpolated variable is an escape sequence and NOT a literal backslash.
Why do you think the first and last quote marks are part of the string? They do not belong to the JSON format. Your program’s behavior looks correct to me.
(Or more precisely, your program seems to be doing exactly what you told it to. Whether your instructions are any good is a question I can’t answer without more context.)
It's hard to tell with the small sample, but it looks like you might be getting quotes from your debugger output. assuming the output of .to_json is a string (usually is), then "#{json_str}" should be exactly equal to json_str. If it isn't, that's a bug in ruby somehow (doubtful).
If you need the quotes, you need to either add them manually or escape the string using whatever escape function is appropriate for your use case. You could use .to_json as your escape function even ("#{json_str.to_json}", for example).

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 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.

What is wrong with this JSON string?

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.