How to make Rails 3 JSON parsing a double-quoted single-line string

Background

On json.org, a string is defined as "char+" , where char+ is one or more char . A char is any unicode character other than " or \ . A subset of control characters is allowed, just avoid them:

"foo" "2" "\\"

In Javascript, if you want to parse a string, it must be enclosed:

"\"foo\"" or '"foo"' , but not "'foo'"

In Rails 3, the JSON gem that runs C or pure Ruby code is by default.


According to the accepted answer, the gem parses JSON documents, not elements. A document is either a collection in the form of a key, value (object / hash), or value (array).


Problem

Lines

Say we want to parse the string foo , we would need to wrap it as "\"foo\"" or '"foo"'

 JSON.parse("\"foo\"") JSON.parse('"foo"') 

Output

 JSON::ParserError unexpected token at '"foo"' 

means he cannot parse "foo"

The numbers

The same applies to numbers: '3' or "3" will give Needs at least two octets . Big numbers (an octet is a byte, so two utf8 characters are two bytes): '42' or "42" just give the same JSON::ParserError unexpected token at '42'


Workaround

A gem parses these things correctly if they are in an array: '["foo"]' or '[3]'

 jsonstring = '"foo"' JSON.parse( "[#{jsonstring}]" )[0] 

gives

 "foo" 


This is ridiculous. Don't I understand something right? Or is this pearl bugged?

+6
source share
1 answer

json.org :

JSON is built on two structures:

  • A collection of name / value pairs. In different languages, this is implemented as an object, record, structure, dictionary, hash table, key list, or associative array.

  • An ordered list of values. In most languages, this is implemented as an array, vector, list, or sequence.

Since "foo" is neither one nor the other, you get an error message. To take a more specific look at Ruby JSON Parser , the statement said:

To create a valid JSON document, you must make sure that this result is embedded in the JSON [] array or JSON {} object. The easiest way to do this is to put your values โ€‹โ€‹in an instance of Ruby Array or Hash.

Therefore, what you refer to as a โ€œworkaroundโ€ is actually the right way to parse a string using a JSON parser.

Additional Information:

Parsing "\"foo\"" on jsonlint.com and json.parser.online.fr causes an error, parsing ["foo"] is being tested on both sites.

+4
source

Source: https://habr.com/ru/post/946178/


All Articles