{
"event": {
"firstEventHeader": {
"domain": "someDomain",
"eventId": "event001",
"priority": "Normal",
"startTimer": timeInMicroSec
},
"secondEventHeader": {
"additionalHeader": [
{
"header": [
{
"Name": "Name1",
"Value": "value1"
},
{
"Name": "Name2",
"Value": "value2"
},
{
"Name": "Name3",
"Value": "value3"
},
],
"name": "Field1"
},
"thirdEventHeader": {
"additionalHeader": [
{
"header": [
{
"Name": "Name4",
"Value": "value4"
},
{
"Name": "Name5",
"Value": "value5"
},
{
"Name": "Name6",
"Value": "value6"
},
],
"name": "Field2"
},
我有一个以上格式的文件,它是使用Python脚本动态生成的。
我想从firstEventHeader访问startTimer,然后从secondEventHeader& thirdEventHeader。 例如
startTimer : 12345678
Name1:value1
Name2:value2
Name3:value3
Name4:value4
Name5:value5
Name6:value6
注意:JSON格式数据在.json以外的其他文件格式中可用。因此加载json将无法正常工作,因为文件格式不同。
答案 0 :(得分:0)
您可以使用json
内置库。假设您可以将json数据转换为某些string
,这应该可以帮助您入门:
import json
d = json.loads(string)
print(d['event']['firstEventHeader']['startTimer'])
您希望进行一些迭代以获得所有Name:Value
对。
答案 1 :(得分:0)
如果文件采用此格式,请使用json模块将其加载到字典中。然后,您可以遍历该字典。
import json
with open('filename') as f:
data == json.load(f)
e = data['event']
print("Start timer:", e['firstEventHeader']['startTimer'])
def process_header(header_fields):
for x in header_fields:
print("Name:", x['Name'], ", Value:", x['Value'])
print("Second event header")
process_header(e['secondEventHeader']['additionalHeader']['header'])
print("Third event header")
process_header(e['thirdEventHeader']['additionalHeader']['header'])