最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Number type in JSON object - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Jun 18, 2015 at 15:40 Plain_Dude_Sleeping_AlonePlain_Dude_Sleeping_Alone 1,8892 gold badges25 silver badges55 bronze badges 2
  • Both are correct, quotes are redundant in this case. – dfsq Commented Jun 18, 2015 at 15:52
  • btw why PHPstorm generates the warning, am I crazy?? – Plain_Dude_Sleeping_Alone Commented Jun 18, 2015 at 15:54
Add a ment  | 

4 Answers 4

Reset to default 5

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.

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./ the results are:

The first verifies as Valid JSON, the second reveals:

    Parse error on line 1:
        {age: 22}
    -----^
    Expecting 'STRING', '}'

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

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

var obj = {
    'foo bar': 0, 
    'foo-bar': 0, 
    '': 0
}
发布评论

评论列表(0)

  1. 暂无评论