从JSON数组中提取和显示值

时间:2015-10-26 12:51:04

标签: javascript php jquery python json

我正在使用Coindesk JSON API获取最新的比特币汇率。

http://api.coindesk.com/v1/bpi/currentprice/GBP.json

我想在我网站的页面上以纯文本显示汇率,例如:“284.0493”。从JSON数组中提取正确值并将其显示在HTML div中的正确方法是什么?

使用JavaScript,PHP甚至Python的任何解决方案都可以。

到目前为止,我一直在this工作。

谢谢!

2 个答案:

答案 0 :(得分:2)

首先,所讨论的json数据不是数组而是对象!

可视化任何json数据的一种简单方法是执行此操作

<?php
$j = '{"time":{"updated":"Oct 26, 2015 12:54:00 UTC","updatedISO":"2015-10-26T12:54:00+00:00","updateduk":"Oct 26, 2015 at 12:54 GMT"},"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org","bpi":{"USD":{"code":"USD","rate":"283.9203","description":"United States Dollar","rate_float":283.9203},"GBP":{"code":"GBP","rate":"185.0732","description":"British Pound Sterling","rate_float":185.0732}}}';

print_r( json_decode($j) );

在这种情况下会产生: -

stdClass Object
(
    [time] => stdClass Object
        (
            [updated] => Oct 26, 2015 12:54:00 UTC
            [updatedISO] => 2015-10-26T12:54:00+00:00
            [updateduk] => Oct 26, 2015 at 12:54 GMT
        )

    [disclaimer] => This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchang
erates.org
    [bpi] => stdClass Object
        (
            [USD] => stdClass Object
                (
                    [code] => USD
                    [rate] => 283.9203
                    [description] => United States Dollar
                    [rate_float] => 283.9203
                )

            [GBP] => stdClass Object
                (
                    [code] => GBP
                    [rate] => 185.0732
                    [description] => British Pound Sterling
                    [rate_float] => 185.0732
                )

        )

)

这非常简单地告诉你a)它的对象具有属性也是对象等等,以及b)如何引用对象中的任何属性。

所以为了得到你想要的汇率我会做: -

<?php
$j = '{"time":{"updated":"Oct 26, 2015 12:54:00 UTC","updatedISO":"2015-10-26T12:54:00+00:00","updateduk":"Oct 26, 2015 at 12:54 GMT"},"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org","bpi":{"USD":{"code":"USD","rate":"283.9203","description":"United States Dollar","rate_float":283.9203},"GBP":{"code":"GBP","rate":"185.0732","description":"British Pound Sterling","rate_float":185.0732}}}';

$bitExchange = json_decode($j);

// the GBP exchange rate will be
echo $bitExchange->bpi->GBP->rate;
// or if you prefer
echo $bitExchange->bpi->GBP->rate_float;

答案 1 :(得分:0)

假设json数据存储在python中的json_text中,您可以执行

import json
json.loads(json_text).get('bpi').get('USD').get('rate')

如果数据对您至关重要,则应检查错误。此外,使货币可配置可能是个好主意。