Python3 处理json数据

Python3 处理json数据

json字符串转对象

import json
data = '{"address":{"city":"北京","country":"中国"},"domain_list":[{"name":"百度","url":"https://www.baidu.com"},{"name":"goole","url":"https://www.google.com"}]}'
obj = json.loads(data)
print(obj['address']['city'])
print(obj['domain_list'][0]['url'])
# 输出结果:
# 北京
# https://www.baidu.com

对象转json字符串

import json
# 字典转json字符串
obj = {
    
    "city": "北京", "country": "中国"}
print(json.dumps(obj, ensure_ascii=False, indent=4))
# 输出结果
# {
    
    
#     "city": "北京",
#     "country": "中国"
# }
import json
# 列表转json字符串
obj = ['Python', 110, True, {
    
    'city': '北京', 'country': '中国'}]
print(json.dumps(obj, ensure_ascii=False, indent=4))
# 输出结果
# [
#     "Python",
#     110,
#     true,
#     {
    
    
#         "city": "北京",
#         "country": "中国"
#     }
# ]

猜你喜欢

转载自blog.csdn.net/BDawn/article/details/109689831