我一直试图解决这个问题,但我不能.我有以下代码:
import json
def jsonblock(filename):
my_array = []
with open(filename) as f:
for line in f:
my_array.append(line)
p = " ".join(str(x) for x in my_array)
return p;
for i in jsonblock('P5.json'):
print(i)
Run Code Online (Sandbox Code Playgroud)
而我的P5.json是
{
"signalPassed" : true,
"location" : {
"longitude" : 113.3910083760899,
"latitude" : 22.57224988908558
},
"phoneOsVersion" : "7.0.3",
"signalStdDev" : 4.139107,
"phoneModel" : "iPad",
}
Run Code Online (Sandbox Code Playgroud)
我想要str格式的正常输出,但是当我这样做时,我得到以下输出:
"
7
.
0
.
3
"
,
"
s
i
g
n
a
l
S
t
d
D
e
v
"
:
4
.
1
3
9
1
0
7
,
}
Run Code Online (Sandbox Code Playgroud)
问题出在哪儿?我怎样才能解决这个问题?
你的函数jsonblock
返回一个字符串,结果为''.join(...)
.对字符串进行迭代会产生单个字符,您可以逐个打印出最后一个字符.
要"解决"你的直接问题,print jsonblock('P5.json')
而不是使用for循环.
但是,您可能想要做的是正确解析json.在这种情况下,请使用json
您已在顶部导入的库.
filename = 'P5.json'
with open(filename, 'rb') as f:
data = json.load(filename)
print data # data is a dictionary in this case
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
139 次 |
最近记录: |