Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does JSON.parse(['1234']) return 1234?

I am having problems understanding the behavior of JSON.parse. JSON.parse should work for only strings. But it seems to work for an array which contains only one string (even single quoted), if the string contains only numbers.

JSON.parse(['1234']) // => 1234 JSON.parse(['1234as']) // => throws error JSON.parse(['123', '123']) // => throws error 
like image 380
Akshendra Pratap Avatar asked May 01 '17 10:05

Akshendra Pratap


People also ask

Does JSON parse throw?

From time to time when working with JSON data, you might stumble into errors regarding JSON formatting. For instance, if you try to parse a malformed JSON with the JSON. parse() function or use the . json() method on the fetch object, it can result in a JavaScript exception being thrown.

How does JSON parse work?

How Does JSON Parse Work? The JSON parse function takes data that's in a text format and then converts it into JavaScript. Usually, these take the form of JavaScript objects, but the parse function can be used directly on arrays as well.

What error does JSON parse () throw when the string to parse is not valid JSON?

JSON. parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.

How do you parse an array of JSON objects?

Example - Parsing JSON Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.


1 Answers

As you have pointed out, JSON.parse() expects a string and not an array. However, when given an array or any other non-string value, the method will automatically coerce it to a string and proceed instead of throwing immediately. From the spec:

  1. Let JText be ToString(text).
  2. ...

The string representation of an array consists of its values, delimited by commas. So

  • String(['1234']) returns '1234',
  • String(['1234as']) returns '1234as', and
  • String(['123', '123']) returns '123,123'.

Notice that string values are not quoted again. This means that ['1234'] and [1234] both convert to the same string, '1234'.

So what you're really doing is:

JSON.parse('1234') JSON.parse('1234as') JSON.parse('123,123') 

1234as and 123,123 are not valid JSON, and so JSON.parse() throws in both cases. (The former isn't legal JavaScript syntax to begin with, and the latter contains a comma operator that doesn't belong.)

1234 on the other hand is a Number literal and therefore valid JSON, representing itself. And that's why JSON.parse('1234') (and by extension JSON.parse(['1234'])) returns the numeric value 1234.

like image 140
BoltClock Avatar answered Sep 30 '22 22:09

BoltClock