我正在从放置在PC本地的JSON文件中提取一些数据: 结构是:
JSON数据示例
{ "totalRecords": 1,
"items": [{
"name": "Services Ltd",
"country": "GB",
"city": "Evesham",
"zip": "WR11 1BY",
"address": "Northwick House\r\rCoopers Lane"
}]
}
Python脚本
import json
from pprint import pprint
fileName = r'naturesmenu.json'
with open(fileName, 'r') as f:
data = json.load(f)
dataData = data["items"]
c = 1
for i in dataData:
# pprint(i)
name = i['name']
address = i['address']
print(address)
针对:
address = i['address']
输出应为:
Northwick House\r\rCoopers Lane
或者如果删除/具有回车的效果,则输出应如下所示:
Northwick House
Coopers Lane
但是我只得到以下输出:
Coopers Lane
不是与address
相对应的完整值。
有人可以指出我在做什么错吗?谢谢
答案 0 :(得分:3)
不带换行符的回车符将移至该行的开头,然后开始覆盖同一行,而不移至下一行。因此,Coopers Lane
会显示在Northwick House
上方,您将看到的输出是
Coopers Laneuse
更改JSON文件,使其包含\n
而不是\r
,这是换行符转义序列。
答案 1 :(得分:1)
您可以选择replace
dataData = data["items"]
c = 1
for i in dataData:
# pprint(i)
name = i['name']
print(name)
address = i['address'].replace('\r',' ')
print(address)
# 'Northwick House Coopers Lane'
或者,如果要在新行中输出,请在\n
中使用replace
address = i['address'].replace('\r','\n')
# Northwick House
# Coopers Lane