简体   繁体   English

如何打印json文件的属性

[英]How to print attributes of a json file

I would appreciate some help: how could I print just the country from the info obtained via this API call?我将不胜感激:如何从通过此 API 调用获得的信息中仅打印国家/地区? Thanks!谢谢!

import requests
import json

 
url = "https://randomuser.me/api/"
data = requests.get(url).json()

print(data)

You should play a little more with the json in order to learn how to use it, a helpful way to understand them is to go layer by layer printing the keys dict.keys() to see where you should go next if you dont have a documentation您应该更多地使用 json 来学习如何使用它,理解它们的一个有用方法是逐层打印键dict.keys()以查看如果您没有下一步应该去哪里文件

in this particular case it returns a dictionary with the following first layer structure:在这种特殊情况下,它返回具有以下第一层结构的字典:

{
"results": [ ... ]
"info": { ... }
}

where results contains a single dictionary inside, therefore we can take其中 results 内部包含一个字典,因此我们可以采用

data['results'][0] to wok with data['results'][0]一起炒锅

there is 'location', and there is a 'country', you can access this in that order to print the country:有“位置”,也有“国家”,您可以按顺序访问它以打印国家:

print(data['results'][0]['location']['country'])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM