将Json输出转换成好看的文本?

2024-09-29 20:22:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从网站检索数据: https://api.coinmarketcap.com/v1/ticker/cardano/?convert=usd

代码段如下所示:

with urllib.request.urlopen("https://api.coinmarketcap.com/v1/ticker/cardano/?convert=USD") as url:
data = json.loads(url.read().decode())
print(data)

输出为:

[{'id':'cardano'、'name':'cardano'、'symbol':'ADA'、'rank':'5'、'price\u-usd':'0.81872'、'price\u-btc':'0.00005809'、'24h\u-volume\u-usd':'213316000.0'、'market\u-cap\u-usd':'2122701191.0'、'available\u-supply':'259270538.0'、'total\u-supply':'31112483745.0'、'max\u-supply':'45000000000.0'、'percent\u-change\u-1,'百分比变化24小时':'13.13','百分比变化7天':'-19.93','上次更新':'1515768856'}]

我的问题是,我该如何处理这些文本?我能把它列成一张好看的单子吗?你知道吗

提前谢谢。你知道吗

附言:我现在正在和Python合作


Tags: httpscomapiurlconvertdata网站price
3条回答

要获得price\u usd元素,可以使用data[0]['price_usd']。你知道吗

您可以使用pprint模块以更好的格式打印它。你知道吗

我非常推荐使用requests库来做这类事情。它非常灵活,是一种事实上的自由库,用于处理有要求的事情。你知道吗

例如(在其中我冒昧地使用了这样的lib和iPython):

In [1]: import requests

In [2]: r = requests.get("https://api.coinmarketcap.com/v1/ticker/cardano/?convert=USD")

In [3]: r.status_code
Out[3]: 200

In [4]: r.json()
Out[4]:
[{'24h_volume_usd': '198429000.0',
  'available_supply': '25927070538.0',
  'id': 'cardano',
  'last_updated': '1515772155',
  'market_cap_usd': '20403048889.0',
  'max_supply': '45000000000.0',
  'name': 'Cardano',
  'percent_change_1h': '-3.09',
  'percent_change_24h': '5.94',
  'percent_change_7d': '-22.7',
  'price_btc': '0.00005650',
  'price_usd': '0.78694',
  'rank': '5',
  'symbol': 'ADA',
  'total_supply': '31112483745.0'}]

In [5]: usd = r.json()[0].get('price_usd')

In [6]: usd
Out[6]: '0.78694'

如果要将响应打印为字符串,可以使用内置的libjson(用于将其转储到文件或其他文件中):

In [8]: import json

In [10]: json.dumps(r.text, indent=2)
Out[10]: '"[\\n    {\\n        \\"id\\": \\"cardano\\", \\n        \\"name\\": \\"Cardano\\", \\n        \\"symbol\\": \\"ADA\\", \\n        \\"rank\\": \\"5\\", \\n        \\"price_usd\\": \\"0.78694\\", \\n        \\"price_btc\\": \\"0.00005650\\", \\n        \\"24h_volume_usd\\": \\"198429000.0\\", \\n        \\"market_cap_usd\\": \\"20403048889.0\\", \\n        \\"available_supply\\": \\"25927070538.0\\", \\n        \\"total_supply\\": \\"31112483745.0\\", \\n        \\"max_supply\\": \\"45000000000.0\\", \\n        \\"percent_change_1h\\": \\"-3.09\\", \\n        \\"percent_change_24h\\": \\"5.94\\", \\n        \\"percent_change_7d\\": \\"-22.7\\", \\n        \\"last_updated\\": \\"1515772155\\"\\n    }\\n]"'

你可以用这样的方法:

print(json.dumps(data, indent=4))

这将变成一个更容易阅读的视图。但我不确定这是否会让你更容易处理脚本中的信息。pprint是另一个很棒的模块。你知道吗

相关问题 更多 >

    热门问题