我有这种格式的json:
{
"fields": {
"tcidte": {
"mode": "required",
"type": "date",
"format": "%Y%m%d"
},
"tcmcid": {
"mode": "required",
"type": "string"
},
"tcacbr": {
"mode": "required",
"type": "string"
}
}
}
我希望它采用数据框格式,其中三个字段名称中的每一个都是单独的行。如果一行有一列(例如“格式”),而其他为空白,则应假定为 NULL。
我曾尝试使用我在此处找到的 flatten_json 函数,但没有按预期工作,但仍将包括在此处:
def flatten_json(nested_json, exclude=['']):
"""Flatten json object with nested keys into a single level.
Args:
nested_json: A nested json object.
exclude: Keys to exclude from output.
Returns:
The flattened json object if successful, None otherwise.
"""
out = {}
def flatten(x, name='', exclude=exclude):
if type(x) is dict:
for a in x:
if a not in exclude: flatten(x[a], name + a + '_')
elif type(x) is list:
i = 0
for a in x:
flatten(a, name + str(i) + '_')
i += 1
else:
out[name[:-1]] = x
flatten(nested_json)
return out
flatten_json_file = pd.DataFrame(flatten_json(nested_json))
pprint.pprint(flatten_json_file)
额外的复杂性 JSON:
{
"fields": {
"action": {
"type": {
"field_type": "string"
},
"mode": "required"
},
"upi": {
"type": {
"field_type": "string"
},
"regex": "^[0-9]{9}$",
"mode": "required"
},
"firstname": {
"type": {
"field_type": "string"
},
"mode": "required"
}
}
}