如何在Python中解析JSON

2024-06-06 10:17:20 发布

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

我有一个JSON文件,我需要它来进行地理定位:

下面是它的样子:

{
"status": "success",
"country": "COUNTRY",
"countryCode": "COUNTRY CODE",
"region": "REGION CODE",
"regionName": "REGION NAME",
"city": "CITY",
"zip": "ZIP CODE",
"lat": LATITUDE,
"lon": LONGITUDE,
"timezone": "TIME ZONE",
"isp": "ISP NAME",
"org": "ORGANIZATION NAME",
"as": "AS NUMBER / NAME",
"query": "IP ADDRESS USED FOR QUERY"

}

实际上,当我发送GET请求时是这样的:

{"as":"AS7922 Comcast Cable Communications, Inc.","city":"Baltimore","country":"United States","countryCode":"US","isp":"Comcast Cable","lat":39.3281,"lon":-76.6385,"org":"Comcast Cable","query":"69.138.1.254","region":"MD","regionName":"Maryland","status":"success","timezone":"America/New_York","zip":"21211"}

如何用Python解析这些数据?输出和打印。你知道吗

谢谢!(很抱歉,如果这是一个副本,我在这里找不到任何帮助我的东西)


Tags: namecitystatuscodezipcountryregionsuccess
1条回答
网友
1楼 · 发布于 2024-06-06 10:17:20

您可以在Python中使用模块json轻松实现这一点。看看这个例子:

#!/usr/bin/env python3

import json


response = {"as":"AS7922 Comcast Cable Communications,    Inc.","city":"Baltimore","country":"United States","countryCode":"US","isp":"Comcast Cable","lat":39.3281,"lon":-76.6385,"org":"Comcast Cable","query":"69.138.1.254","region":"MD","regionName":"Maryland","status":"success","timezone":"America/New_York","zip":"21211"}

data_str = json.dumps(response)  # serialize object in JSON format string

data = json.loads(data_str)   #  deserialize JSON string to Python object

print ('{} \n'.format(data_str))
print ('{} \n'.format(data))


# show all itens
for key in response:
    print ('{} -> {}'.format(key, response[key]))

print ('#' * 100)

for key in data:
    print ('{} -> {}'.format(key, data[key]))

相关问题 更多 >