Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Number type in JSON object

I just started to learn JSON :

which one of the following is correct :

var json = {"age":22} // my book writes like this

or

var json = {age:22} // internet show example like this

PHP storm generates

argument type number is not assignable  to parameter type string 

for both of them.

If the second one is correct show what is the difference with JS object then.

like image 372
Plain_Dude_Sleeping_Alone Avatar asked Jun 18 '15 15:06

Plain_Dude_Sleeping_Alone


4 Answers

Well, you're using the term JSON, but the example you show isn't JSON. If you're talking about plain JavaScript objects, then both examples you gave are correct. When people refer to JSON, they're usually referring to the data type sent over client/server exchanges, which is very specific, and there are linters for that (see jsonlint, for example). PHPStorm's error is incorrect.

output

like image 163
Josh Beam Avatar answered Oct 02 '22 14:10

Josh Beam


When working with JSON a validator/linter is an essential tool, especially dealing with larger sets of data.

Sending both of these through http://jsonlint.com/ the results are:

The first verifies as Valid JSON, the second reveals:

    Parse error on line 1:
        {age: 22}
    -----^
    Expecting 'STRING', '}'
like image 34
simsom Avatar answered Oct 02 '22 14:10

simsom


Basically JSON are key value pairs , its basically object for storing data

  • var json = {"age":"22"} : if you use like this you can get value like json["age"] and json.age , both are helpful in certain situations and value returned is string , you need to convert it (only its required)
  • var json = {age :22 } : if you use like this you cant get value like json[""] format , only json.age can be used to get
  • var json = {"age":22} should be fine as your using type as number and moreover you can fetch it using json["age"]

The above scenarios mentioned are respect to your functionalites and usage of them

like image 29
Shushanth Pallegar Avatar answered Oct 02 '22 16:10

Shushanth Pallegar


Both ways are valid in Javascript. But the quotes are needed in specific cases, like :

var obj = {
    'foo bar': 0, 
    'foo-bar': 0, 
    '': 0
}
like image 38
R3tep Avatar answered Oct 02 '22 15:10

R3tep