如何使用循环并插入变量来解析json对象?

时间:2019-03-05 13:16:23

标签: javascript json

我有一个json对象,如下所示:

DISPLAY={EOS={USD={LASTTRADEID=341887636, OPEN24HOUR=$ 3.27, HIGHDAY=$ 3.51, LOW24HOUR=$ 3.26, TOTALVOLUME24HTO=$ 830.73 M, TOSYMBOL=$, LASTVOLUME=EOS 24.15, LASTMARKET=Bitfinex, LOWHOUR=$ 3.43, MKTCAP=$ 3,625.98 M, LASTUPDATE=Just now, TOTALVOLUME24H=EOS 237.50 M, VOLUMEHOURTO=$ 1,059,991.8, VOLUMEHOUR=EOS 304,460.7, CHANGEDAY=$ 0.20, SUPPLY=EOS 1,035,994,216.9, IMAGEURL=/media/1383652/eos_1.png, VOLUMEDAY=EOS 2,599,959.7, VOLUME24HOUR=EOS 3,649,420.2, MARKET=CryptoCompare Index, PRICE=$ 3.50, CHANGEPCTDAY=6.06, FROMSYMBOL=EOS, LASTVOLUMETO=$ 84.63, CHANGEPCT24HOUR=7.03, OPENDAY=$ 3.30, VOLUMEDAYTO=$ 8,793,658.5, OPENHOUR=$ 3.44, CHANGE24HOUR=$ 0.23, HIGH24HOUR=$ 3.51, VOLUME24HOURTO=$ 12,252,312.4, LOWDAY=$ 3.27, HIGHHOUR=$ 3.51}}}, RAW={EOS={USD={LASTTRADEID=341887636, OPEN24HOUR=3.27, HIGHDAY=3.51, LOW24HOUR=3.26, TOTALVOLUME24HTO=8.307307946338731E8, TOSYMBOL=USD, LASTVOLUME=24.14719568, LASTMARKET=Bitfinex, LOWHOUR=3.43, MKTCAP=3.6259797592476497E9, LASTUPDATE=1551791305, TOTALVOLUME24H=2.3750041516530967E8, VOLUMEHOURTO=1059991.8469860656, VOLUMEHOUR=304460.70931976027, CHANGEDAY=0.20000000000000018, FLAGS=4, SUPPLY=1.0359942169279E9, TYPE=5, IMAGEURL=/media/1383652/eos_1.png, VOLUMEDAY=2599959.6798382923, VOLUME24HOUR=3649420.2367477496, MARKET=CCCAGG, PRICE=3.5, CHANGEPCTDAY=6.060606060606066, FROMSYMBOL=EOS, LASTVOLUMETO=84.62626198012799, CHANGEPCT24HOUR=7.033639143730887, OPENDAY=3.3, VOLUMEDAYTO=8793658.516717305, OPENHOUR=3.44, CHANGE24HOUR=0.22999999999999998, HIGH24HOUR=3.51, VOLUME24HOURTO=1.225231238390642E7, LOWDAY=3.27, HIGHHOUR=3.51}}}}

我可以通过以下方式获取价格:

resp.DISPLAY.EOS.USD.PRICE

但是,我想在多个符号的循环中执行此操作,因此我希望能够执行以下操作:

resp.DISPLAY' + symbol + '.USD.PRICE

这不起作用,并且我收到各种错误消息,包括“参数列表后缺少”)。

所以问题是如何正确构建字符串,插入变量符号,以访问JSON对象中的元素?

谢谢!

1 个答案:

答案 0 :(得分:0)

resp.DISPLAY[symbol].USD.PRICE