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

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

Asked on October 23, 2018 in Json.
Add Comment


  • 3 Answer(s)

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

    • String([‘1234’]) returns ‘1234’,
    • String([‘1234as’]) returns ‘1234as’,
    • String([‘123’, ‘123’]) returns ‘123,123’.

    that string values are only once quoted . This means that [‘1234’] and [1234] both convert to the same string, ‘1234′.

    What It really happens that

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

    1234 as and 123,123 are not valid JSON, and so JSON.parse() throws in both cases

    Answered on October 23, 2018.
    Add Comment

    If JSON.parse doesnt get a string, it will first convert the input to string.

    ["1234"].toString() // "1234"
    ["1234as"].toString() // "1324as"
    ["123","123"].toString() // "123,123"
    

    From all those outputs it only knows how to parse “1234”.

     

    Answered on October 23, 2018.
    Add Comment
    JSON.parse(['1234'])
    // Becomes JSON.parse("1234")
    // 1234 could be parsed as a number
    // Result is Number 1234
     
    JSON.parse(['1234as'])
    // Becomes JSON.parse("1234as")
    // 1234as cannot be parsed as a number/true/false/null
    // 1234as cannot be parsed as a string/object/array either
    // Throws error (complains about the "a")
     
    JSON.parse(['123', '123'])
    // Becomes JSON.parse("123,123")
    // 123 could be parsed as a number but then the comma is unexpected
    // Throws error (complains about the ",")
    

    The above code can be used to return 1234.

    Answered on October 23, 2018.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.