使用子字符串从JSON对象检索数据

时间:2016-08-04 16:13:08

标签: javascript json

如果我有以下JSON对象:

taxcodes = {
   "CA_MONO CO": {
          "Rate": 1,
          "Country": "United States"
       }
}

使用taxcodes["CA_MONO CO"].Rate可以完美地检索1

的比率

现在我的问题是,如果我有一个变量,请说:x = "CA_MONO CO_MAMMOTH LAKES"

由于taxcodes[x].Rate

_MAMMOTH LAKES显然无效。

所以我所做的就是在CO_之后删除所有字符串,这会给我CA_MONO然后将' CO'重新添加到字符串的末尾,这会给我CA_MONO CO

var modifiedx = x.substring(0, x.indexOf('CO_')) + ' CO';

然后我尝试使用taxcodes[modifiedx].Rate来提取数据,而{{1}}没有提取数据。

3 个答案:

答案 0 :(得分:1)

附加

时,您有一个额外的空格



.bar .button.button-clear .icon:before{
  font-size: 12px;
}




答案 1 :(得分:0)

那是因为你有SyntaxError: missing ; before statement @(shell)的额外空间。因此值为$ mongo MongoDB shell version: 3.2.8 connecting to: test Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see http://docs.mongodb.org/ Questions? Try the support group http://groups.google.com/group/mongodb-user Server has startup warnings: 2016-08-04T11:58:21.138-0400 I CONTROL [initandlisten] 2016-08-04T11:58:21.138-0400 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'. 2016-08-04T11:58:21.138-0400 I CONTROL [initandlisten] ** We suggest setting it to 'never' 2016-08-04T11:58:21.138-0400 I CONTROL [initandlisten] 2016-08-04T11:58:21.139-0400 I CONTROL [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'. 2016-08-04T11:58:21.139-0400 I CONTROL [initandlisten] ** We suggest setting it to 'never' 2016-08-04T11:58:21.139-0400 I CONTROL [initandlisten] > show dbs mydb 0.000GB local 0.000GB > use mydb switched to db mydb > show collections 201607012 > db mydb > mydb.201607012.find() 2016-08-04T12:10:23.826-0400 E QUERY [thread1] SyntaxError: missing ; before statement @(shell):1:4 > db.201607012.find() 2016-08-04T12:10:29.000-0400 E QUERY [thread1] SyntaxError: missing ; before statement @(shell):1:2 > db.201607012.find() 2016-08-04T12:11:09.115-0400 E QUERY [thread1] SyntaxError: missing ; before statement @(shell):1:2 > db.201607012.stats() 2016-08-04T12:13:06.022-0400 E QUERY [thread1] SyntaxError: missing ; before statement @(shell):1:2 而不是' CO'。只需删除它:

"CA_MONO  CO"

答案 2 :(得分:0)

var modifiedx = x.substring(0, x.indexOf('CO_')) + ' CO';

应该是

var modifiedx = x.substring(0, x.indexOf('CO_')) + 'CO';