Parse.com says "invalid character '\'' looking for beginning of value" - json

When I click finish import, Parse.com says "invalid character '\'' looking for beginning of value". However, there is not a single character "\" in my entire file. You can check it below.
Apparently, this is because of using single quotes instead of double quotes.
Can I use "name": 'Samat', instead of "name": "Samat"?
https://gist.github.com/samatdav/61db29a676da21dc4bbd

The JSON format specification is very clear about this: String values must be enclosed in double quotes. Single quotes or unquoted values (other than true, false, null, numbers or nested object/array definitions) are not allowed.
JavaScript's internal object notation is much less strict in that regard, as it generally allows single-quoted strings. However, JSON is only a subset of the original JavaScript object notation syntax.

For anyone that might need this later.
As ipfs daemon --help suggests, the cors domain can be set via
>ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin '["*"]'
which in Windows yields
Error: failed to unmarshal json. invalid character '\'' looking for beginning of value
The correct version should be
>ipfs config --json API.HTTPHeaders.Access-Control-Allow-Origin "[\"*\"]"

The error itself is telling you the invalid character is ' the single quote. It's just represented as a \' since they are using single quotes to enclose the invalid character the character must be escaped.
"invalid character '\'' looking for beginning of value"
^ ^ notice the single quotes.
The issue in your gist is that single quotes are not valid representation of strings in JSON.
Note
{
"foo": 'bar'
}
Yields the following error on JSONLint
Parse error on line 2:
{ "foo": 'bar'}
------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

Related

Nifi: Delimiters in Nifi

I was working on a task and got an error. Which says that invalid char between encapsulated token and delimiter.
Here is the SS of the data
For line 08, I was using the pipe as a delimiter, and the escape character was '^'. For line 12 I was using the comma as a delimiter. The highlighted part is the issue. If I remove the cap sign from line 08 and a single quote from line 12 it runs with success.
The processor is ConverRecord and here is the screenshot of the configs of the processor.
Actually, I am using two processors of ConvertRecord. In one processor the fields separator is a comma(,) whereas in the second processor the fields separator is also comma(,) but the escape character is Cap sign(^).
assume that these are two different records.
Why it is throwing error at that point? And how can I solve this issue?
Thanks in advance.
For the first sample data (line 08), configure CSVReader as:
Quote Character: "
Escape Character: \
Value Separator(delimiter): |
For the second sample data (line 12), configure CSVReader as:
Quote Character: "
Escape Character: \
Value Separator(delimiter): ,
The reason for failure is that your data does not conform with delimited data specifications i.e. data is invalid, so you need to add upstream cleanup logic.
For line 08 data - you have used escape character as ^ and same is appeared in the data as well, so when CSVReader encountered ^" it escaped " because of this opening double quote does not have a corresponding closing double quote causing to throw the exception. So setting Escape Character: \ property will resolve the issue. \ is kind of widely used escape character, so it is very rare to get \ as a part of data.
For line 12 data - seems like single quote ' is used as Quote Character and missing a corresponding closing quote character i.e. ' causing to throw the exception. You need to devise a logic that will add the missing closing quote character wherever required. A workaround would be to use Quote Character: " so that ' will be the part of the data and then you can clean it at downstream eg. if you are putting data into a table then post-ingestion updating the column to remove '

Not able to parse the character ! parameter in spark job server

I am trying to submit a spark job in spark job server with input in json format. However in my case one of values contains '!' character, which is not allowing me to parse it.Here is my input and response.
Input
curl -d "{"test.input1"="abc", "test.input2"="def!"}" 'http://localhost:8090/jobs?appName=my_spark_job&classPath=com.example.spark.job.MySparkJob'
Response
"result": "Cannot parse config: String: 1: Reserved character '!' is not allowed outside quotes (if you intended '!' (Reserved character '!' is not allowed outside quotes) to be part of the value for 'test.input2', try enclosing the value in double quotes, or you may be able to rename the file .properties rather than .conf)"
The value of "test.input2" is already in double quotes. I tried adding single/double quotes but still didnt work. Any thoughts how can i parse it.
Thanks
Put everything in a json file and do the following
curl --data-binary #/path/to/json/file 'http://localhost:8090/jobs?appName=my_spark_job&classPath=com.example.spark.job.MySparkJob'

How does parsing special characters in JSON work?

Alright, I know i’m probably going to get yelled at for asking such a ‘simple’ question (seems to be the trend around here) but check it out…
I am building a JSON parser and got everything working correctly except the parsers ability to deal with special characters. I am trying to implement the same special characters that are listed on http://www.json.org/ namely, [", \, /, b, f, n, r, t, u].
When I run these special characters through the builtin JSON.parse method though, most of them either return an error or don’t do anything at all
JSON.parse('["\\"]')
SyntaxError: Unexpected end of input
JSON.parse("['\"']")
SyntaxError: Unexpected token ‘
JSON.parse('["\b"]')
SyntaxError: Unexpected token
JSON.parse('["\f"]')
SyntaxError: Unexpected token
Yes, I see the other post "Parsing JSON with special characters", it has nothing to do with my question. Don't refer me to another question, I have seen them all. How does parsing special characters in JSON work?
JSON.parse expects JavaScript strings.
JavaScript string literals use backslashes for escaping.
JSON uses backslashes for escaping.
So...
JSON.parse('["\\\\"]')
// ["\"]
JSON.parse("['\"']")
// SyntaxError: Unexpected token '
// JSON doesn't have single quotes as string delimiters!
JSON.parse('["\\b"]')
// [""]
JSON.parse('["\\f"]')
// [""]
JSON.parse('["\\\\b"]')
// ["\b"]
JSON.parse('["\\\\f"]')
// ["\f"]
The reason you've got an issue here is because \ is also a marker for special characters within javascript strings.
Take your first example: '["\\"]'. As javascript parses this string, \\ is escaped to a single \ in your string, so the value passed to JSON.parse method is actually ["\"] - hence the "unexpected end of input error".
Essentially, you need to cater for the javascript parser by doubling-up on the backslash escape sequences. In this case, to pass your intended ["\\"] value to JSON.parse, you need to use JSON.parse('["\\\\"]') in javascript as that will pass the string ["\\"] into the JSON.parse method.

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

Why this JSON is invalid?

I have tried to send some emails to my php server as json format,but when I validate that json it shows some error
{"function":"contacts", "parameters": {"emails": "(
"John#mac.com",
"anna#gmail.com",
"hank#mac.com"
)","user_id": "90"},"token":""}
Error shows as -
Parse error on line 4:
...{ "emails": "( "John#ma
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
You need to use square brackets for all arrays. Right now you are using parenthesis and you also start with a quotation indicating a string instead of an array.
Either you want the whole value to be a string in which you should be escaping the quotes within the string with a "\" or you should remove the quote and replace the parenthesis with square brackets.
Note: The syntax highlighting above should hint at where you are going wrong.
You need to change you JSON to the following. Or you need to escape the double quotes surrounding the email addresses.
{"function":"contacts", "parameters": {"emails": [
"John#mac.com",
"anna#gmail.com",
"hank#mac.com"
],"user_id": "90"},"token":""}
Your emails element is being defined as a string starting with "( and ending with )".
Inside that string, you then have separate strings each starting and ending with quote marks.
This is obviously incorrect.
What you probably intended is "emails" : [ ...... ]
(... unless you actually intended for the emails element to be a string, in which case the quotes within it need to be escaped as \", as do the line feeds as \n. but I don't think that's what you intended, is it?).
That's why you're getting a syntax error.
However I guess The key point here is that issues like this demonstrate why it is a bad idea to hand-write JSON code (or indeed other text-based syntaxes like XML). You should always use an encoder or decoder to create your JSON strings from within the language you're working with. This will avoid you ever having to deal with issues like this; if you use an encoder, your JSON will always be valid; you don't need to worry about it.
Hope that helps.
Your array appears to be delimited with "(...)" instead of [..]. Among other things, this makes the strings inside it "inside out". If you meant for it to be a quoted string that just resembles an array, you'll need to escape the quotes inside it, like foo \"and\" bar. The flow-chart at http://www.json.org/ is really quite useful, as it is a very small spec.
I am guessing you want:
{
"function":"contacts",
"parameters": {
"emails": [
"John#mac.com",
"anna#gmail.com",
"hank#mac.com"
],
"user_id": "90"
},
"token":""
}