全新的Python并尝试解析如下所示的JSON数组:
[
{"Event":"start","EventDateTime":"2015-09-15T03:45:16.681428Z"},
{"Event":"process","EventDateTime":"2015-09-15T03:45:16.681428Z"},
{"Event":"end","EventDateTime":"2015-09-15T03:45:16.681428Z"}
]
我需要将输出放在字符串制表符分隔的字段和新行分隔的行上,如下所示:
start \t 2015-09-15T03:45:16.681428Z \n
process \t 2015-09-15T03:45:16.681428Z \n
end \t 2015-09-15T03:45:16.681428Z
这是我到目前为止的代码:
import json
if not j or not i:
return None
try:
arr = json.loads(j)
except ValueError:
return None
if len(arr) <= 0:
return None
row=i
for li in arr
elem = json.loads(li, object_pairs_hook=collections.OrderedDict)
row=row + '\t' + elem.Key + '\t' + elem.Value + \n
return row
首先我得到,缩进错误,修复了缩进,但收到了关于未定义的'集合'的错误。
有没有办法在不使用该集合的情况下完成我需要的工作。当我删除集合对象时,我得到其他错误。
谢谢!
答案 0 :(得分:2)
import json
j = """[
{"Event":"start","EventDateTime":"2015-09-15T03:45:16.681428Z"},
{"Event":"process","EventDateTime":"2015-09-15T03:45:16.681428Z"},
{"Event":"end","EventDateTime":"2015-09-15T03:45:16.681428Z"}
]"""
j = json.loads(j)
for item in j:
print '%s\t%s' % (item['Event'], item['EventDateTime'])
答案 1 :(得分:1)
如下:
j = '''[
{"Event":"start","EventDateTime":"2015-09-15T03:45:16.681428Z"},
{"Event":"process","EventDateTime":"2015-09-15T03:45:16.681428Z"},
{"Event":"end","EventDateTime":"2015-09-15T03:45:16.681428Z"}
]
'''
import json
content = json.loads(j)
keys = content[0].keys()
for i in content:
print(' \t '.join([i[k] for k in keys]) + '\n')
答案 2 :(得分:1)
鉴于OP正在使用OrderedDict钩子,那么你可以在不参考名称的情况下做到这一点:
arr = json.loads(j, object_pairs_hook=collections.OrderedDict)
for item in arr:
print(' \t '.join(item.values()))