On the json.org website, a string is defined as "char+"
where char+
is one or more char
. A char
is any unicode character except "
or \
. A subset of control characters are allowed, just escape them:
"foo"
"2"
"\\"
In Javascript, if you want to parse a string, it needs to be enclosed:
"\"foo\""
or '"foo"'
, but not "'foo'"
In Rails 3, the JSON gem that runs C or pure Ruby code is default.
As per the accepted answer, the gem parses JSON documents rather than elements. A document is either a collection in the form of key, value (object/hash) or values (array).
Let's say we want to parse the string foo
, We would need to enclose it as "\"foo\""
or '"foo"'
JSON.parse("\"foo\"")
JSON.parse('"foo"')
yield
JSON::ParserError unexpected token at '"foo"'
meaning it can't parse "foo"
The same goes for numbers: '3'
or "3"
will yield Needs at least two octets
.
Larger numbers ( an octet is a byte, so two utf8 characters are two bytes ): '42'
or "42"
simply yield the same JSON::ParserError unexpected token at '42'
The gem correctly parses these things if they are in an array: '["foo"]'
or '[3]'
jsonstring = '"foo"'
JSON.parse( "[#{jsonstring}]" )[0]
yields
"foo"
This is ridiculous. Am I not understanding something correctly? Or is this gem bugged?
Strings in JSON are specified using double quotes, i.e., " . If the strings are enclosed using single quotes, then the JSON is an invalid JSON .
Yes. Properties in JSON have to be strings, and in JSON as string is defined as "a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes". In other words using single quotes, or no quotes at all is not allowed.
What is JSON? JSON is short for Javascript Object Notation. It is the simplest and easiest way to transfer data using the internet which makes the language extremely popular for APIs, enabling developers to work across multiple languages.
json.org states:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
Since "foo"
is neither of the above you are getting the error message. To further concrete it have a look at Ruby JSON Parser, the documenation states:
To create a valid JSON document you have to make sure, that the output is embedded in either a JSON array [] or a JSON object {}. The easiest way to do this, is by putting your values in a Ruby Array or Hash instance.
Hence what you are mentioning as "workaround" is actually the correct way to parse a string using the JSON parser.
Additional Info:
Parsing "\"foo\""
on jsonlint.com and json.parser.online.fr raises an error,
parsing ["foo"]
passes the validation test on both the sites.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With