将包含JSON对象的JSON对象简化为[Path,Value]形式的数组,可以通过递归遍历JSON对象的每个属性来实现。以下是一个示例代码:
def simplify_json(json_obj, path='', result=[]):
if isinstance(json_obj, dict):
for key, value in json_obj.items():
new_path = path + '/' + str(key)
if isinstance(value, (dict, list)):
simplify_json(value, new_path, result)
else:
result.append([new_path, value])
elif isinstance(json_obj, list):
for index, value in enumerate(json_obj):
new_path = path + '/' + str(index)
if isinstance(value, (dict, list)):
simplify_json(value, new_path, result)
else:
result.append([new_path, value])
return result
这个函数接受一个JSON对象作为输入,并返回一个简化后的数组,其中每个元素都是一个包含路径和对应值的列表。路径表示了JSON对象中每个值的位置,以斜杠分隔层级关系。
例如,对于以下JSON对象:
{
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York"
},
"hobbies": ["reading", "coding"]
}
使用上述函数将其简化为数组形式:
json_obj = {
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York"
},
"hobbies": ["reading", "coding"]
}
result = simplify_json(json_obj)
print(result)
输出结果为:
[
["/name", "John"],
["/age", 30],
["/address/street", "123 Main St"],
["/address/city", "New York"],
["/hobbies/0", "reading"],
["/hobbies/1", "coding"]
]
这样,我们将包含JSON对象的JSON对象简化为了[Path,Value]形式的数组。这种形式的数据在处理和分析JSON数据时非常有用,可以方便地定位和提取特定路径下的值。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云