发生原因
在我尝试利用python读取JSON文件时,发生了乱码。JSON示例,python代码如下:
json文件:
[
{
"name" : "张三",
"age" : 18,
"id" : "42060219970315"
},
{
"name" : "LiSi",
"age" : 20,
"id" : "42060219960416"
}
]
python代码:
#-*- coding = utf-8 -*-
#@Time: 2021/5/10 14:28
#@Author: PeterY
#@File: demo01.py
#@Software: PyCharm
from py2neo import Node,Graph,Relationship,NodeMatcher
import json
graph = Graph(
"http://localhost:7474",
auth = ('neo4j','123456')
)
filePath = "./data/data.json"
#读取JSON数据,转换为list
with open(filePath) as f:
#peopleList = json.loads(f.read())
peopleList = json.load(f)
#遍历List集合
for person in peopleList:
print(person['name'])
p = Node("person",name=person['name'],age=person['age'],id = person['id'])
graph.create(p)
此时,person['name']
本应该为“张三”,但是发生乱码。但是我的pycharm中的文件编码全部都已经设置成了UTF-8。上网查询解决方法,但使用后仍未解决问题。直到我指定open()方法的打开文件方式:
with open(filePath,encoding='utf-8') as f:
peopleList = json.load(f)
问题便解决了。