json的使用

650 阅读1分钟

json字符串生成json对象

import json

str = '''
[{
    "name": "Bob",
    "gender": "male",
    "birthday": "1992-10-18"
}, {
    "name": "Selina",
    "gender": "female",
    "birthday": "1995-10-18"
}]
'''
print(type(str))
data = json.loads(str)
print(data)
print(type(data))

json双引号,不能使用单引号

import json

str = '''
[{
    'name': 'Bob',
    'gender': 'male',
    'birthday': '1992-10-18'
}]
'''
data = json.loads(str)

"""
json字符串的key-value都需要使用双引号,不能使用单引号,否则在loads的时候会报错
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 3 column 5 (char 8)
"""

文件读取json内容

import json

with open('data.json', 'r') as file:
    str = file.read()
    data = json.loads(str)
    print(data)

json写入文件

  • json.dumps()会自动将json串中的单引号变成双引号
import json

data = [{
    'name': 'Bob',
    'gender': 'male',
    'birthday': '1992-10-18'
}]
with open('data.json', 'w') as file:
    file.write(json.dumps(data))

json写入文件,indent指定缩进

import json

data = [{
    'name': 'Bob',
    'gender': 'male',
    'birthday': '1992-10-18'
}]
with open('data.json', 'w') as file:
    file.write(json.dumps(data, indent=2))

"""
文件中的文本格式
[
  {
    "name": "Bob",
    "gender": "male",
    "birthday": "1992-10-18"
  }
]
"""

中文解码问题

import json

data = [{
    'name': '李宁',
    'gender': '男',
    'birthday': '1992-10-18'
}]

with open('data.json', 'w', encoding='utf-8') as file:
    file.write(json.dumps(data, indent=2, ensure_ascii=False))

"""
存在中文
with open('data.json', 'w') as file:
    file.write(json.dumps(data, indent=2))
[
  {
    "name": "\u738b\u4f1f",
    "gender": "\u7537",
    "birthday": "1992-10-18"
  }
]

解决方式:
with open('data.json', 'w', encoding='utf-8') as file:
    file.write(json.dumps(data, indent=2, ensure_ascii=False))
"""