python json模块

本文介绍了Python中JSON数据的编码与解码方法,包括json.dumps与json.loads的使用示例,以及如何将Python对象编码成JSON字符串并保存到文件中。此外,还列举了多个用于通过IP地址查询地理位置信息的API接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写。
json.dumps : 将Python对象编码澄JSON字符串
json.loads : 将已编码的JSON字符串解码为Python对象

举例:

import json
# 将python对象编码成为json的字符串格式;
d = {'name': 'fentiao'}
jsonStr = json.dumps(d)
print(jsonStr)
print(type(jsonStr))

l = [1, 2, 3, 4]
jsonLi = json.dumps(l)
print(jsonLi, type(jsonLi))

这里写图片描述

import json
# 将python对象编码成为json的字符串格式;
d = {'name': 'fentiao'}
jsonStr = json.dumps(d)
# 将获取的json字符串解码为python的对象
pythonDict = json.loads(jsonStr)
print(pythonDict, type(pythonDict))

这里写图片描述

import json
# 将python对象编码成为json的字符串格式;
d = {'name': 'fentiao'}
jsonStr = json.dumps(d)
# 将python对象编码成为json的字符串格式并写入文件中;
with open('json.txt', 'w') as f:
    json.dump(d, f)

这里写图片描述

import json
# 将python对象编码成为json的字符串格式;
d = {'name': 'fentiao'}
jsonStr = json.dumps(d)
 # 将文件中的json字符串解码为python的对象
with open('json.txt') as f:
    json_Dict = json.load(f)
    print(json_Dict, type(json_Dict))

这里写图片描述

    根据IP查询所在地、运营商等信息的一些API如下:
    1. 淘宝的API(推荐):http://ip.taobao.com/service/getIpInfo.php?ip=110.84.0.129
    2. 国外freegeoip.net(推荐):http://freegeoip.net/json/110.84.0.129 这个还提供了经纬度信息(但不一定准)
    3. 新浪的API:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=110.84.0.129
    4. 腾讯的网页查询(返回的非json格式): http://ip.qq.com/cgi-bin/searchip?searchip1=110.84.0.129
    5. ip.cn的网页(返回的非json格式):http://www.ip.cn/index.php?ip=110.84.0.129
    6. ip-api.com: http://ip-api.com/json/110.84.0.129
上述的API接口,大多有一个特点是, 返回的直接是个json格式;
# ip = input('IP:')
import json
from urllib.request import urlopen

# ip = '8.8.8.8'
ip = input("请输入查询的IP:")
url = "http://ip.taobao.com/service/getIpInfo.php?ip=%s" %(ip)

# 根据url获取网页的内容, 并且解码为utf-8格式, 识别中文;
text  = urlopen(url).read().decode('utf-8')
# print(text)
# print(type(text))

# 将获取的字符串类型转换为字典, 方便处理
d = json.loads(text)['data']
country = d['country']
city = d['city']
print(country, city)

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值