python json文件读写

一、json介绍

json中有两种数据结构:字典{}和列表[]

{
    "name": "熊猫",
    "like": [
      "听歌",
      "看书",
      "运动"
    ],
    "address": {
      "country": "中国",
      "city": "上海"
    }
  }

json中的字符串必须使用双引号

添加注释//或者/**/在json文件中是不允许的,那么JSON如何才能添加注释?可以使用key : value在json中增加一个充当注释的数据元素

二、python读取json文件

json.load():

import json  # 导入包

with open('Info.json', encoding='utf-8') as a:
    result = json.load(a)  # 导入json文件,a是文件对象,result是一个字典
    print(result.get('name'))  # 熊猫
    print(result.get('address').get('city'))  # 上海

三、python写入json文件

python中的字典和序列(列表或元组)可以写入json文件

json.dump():

my_list = [('熊猫', '听歌', '上海'), ('老虎', '运动', '北京')]
with open('Info2.json', 'w', encoding='utf-8') as b:
    json.dump(my_list, b, ensure_ascii=False, indent=2)  # 不以ASCII的方式显示(显示中文),indent 缩进

Info2.json:

[
  [
    "熊猫",
    "听歌",
    "上海"
  ],
  [
    "老虎",
    "运动",
    "北京"
  ]
]

四、python字典或序列转换成json字符串

json.dumps()

import json
 
data = {"hi" : "你好", "who" : "全世界"}
json_str = json.dumps(data, indent=4, ensure_ascii=False)  # 缩进4,显示中文
print(json_str)

'''
输出:
{
    "hi": "你好",
    "who": "全世界"
} 
'''

参考:

json文件怎么加注释?-js教程-PHP中文网

python——json文件的读取 - 非同凡响 - 博客园 (cnblogs.com)

Python3:json.dumps 缩进显示,处理中文,排序输出,指定分隔符_python3 json.dumps_风静如云的博客-CSDN博客

猜你喜欢

转载自blog.csdn.net/qq_41021141/article/details/128832785