基于分隔符将多行字符串转换为JSON



我真的不知道如何将多行字符串转换为JSON树结构

因此,我在一个特定的excel列下有多行字符串,如下所示:

/abc/a[2]/a/x[1]
/abc/a[2]/a/x[2]

由于上面的字符串包含分隔符/,我可以使用它们来创建父子关系,并将它们转换为Python字典(或(JSON,如下所示:

{
"tag": "abc",
"child": [
{
"tag": "a[2]",
"child": [
{
"tag": "a",
"child": [
{
"tag": "a",
"child": [
{
"tag": "x[1]"
},
{
"tag": "x[2]"
}
]
}
]
}
]
}
]
}

我无法为我的项目的这一部分提出逻辑,因为我需要寻找[1]、[2]的存在,并将它们分配给一个公共父级,这需要以某种递归的方式来完成,这种方式适用于任何长度的字符串。请帮助我使用Python中的任何代码逻辑,或者为我提供建议。非常感谢!!

附加更新:只是想知道是否也可以在JSON结构中包含其他列的数据。

例如:如果excel包含以下三列和两行

标签/abc/a[2]/a/x[1]你好string/abc/a[2]/a/x[2]世界字符串

您可以将递归与collections.defaultdict:一起使用

import collections, json
def to_tree(d):
v = collections.defaultdict(list)
for [a, *b], *c in d:
v[a].append([b, *c])
return [{'tag':a, **({'child':to_tree(b)} if all(j for j, *_ in b) else dict(zip(['text', 'type'], b[0][-2:])))} 
for a, b in v.items()]
col_data = [['/abc/a[2]/a/x[1]', 'Hello', 'string'], ['/abc/a[2]/a/x[2]', 'World', 'string']] #read in from your excel file
result = to_tree([[[*filter(None, a.split('/'))], b, c] for a, b, c in col_data])
print(json.dumps(result, indent=4))

输出:

[
{
"tag": "abc",
"child": [
{
"tag": "a[2]",
"child": [
{
"tag": "a",
"child": [
{
"tag": "x[1]",
"text": "Hello",
"type": "string"
},
{
"tag": "x[2]",
"text": "World",
"type": "string"
}
]
}
]
}
]
}
]
def to_dict(data, old_data=None):
json={}
if old_data!=None:
json["child"]=old_data
for row in data.split("n"):
path=json
for element in row.strip("/").split("/"):
if not "child" in path:
path["child"]=[]
path=path["child"]
for path_el in path:
if element==path_el["tag"]:
path=path_el
break
else:
path.append({"tag":element})
path=path[-1]
return json["child"]
#tests:
column="""/abc/a[2]/a/x[1]
/abc/a[2]/a/x[2]"""
print(to_dict_2(column))
print(to_dict_2(column,[{'tag': 'abc', 'child': [{'tag': 'old entry'}]}]))

您可以使用ndjson包(我与之没有关联,但我是一些成功用户(。要安装,

pip install ndjson

在他们的例子中,

import ndjson
# load from file-like objects
with open('data.ndjson') as f:
data = ndjson.load(f)
# convert to and from objects
text = ndjson.dumps(data)
data = ndjson.loads(text)
# dump to ndjson file-like object
with open('backup.ndjson', 'w') as f:
ndjson.dump(data, f)

因此,你只需遵循以下内容即可:

import json
# dump to json file-like object
with open('backup.json', 'w') as f:
json.dump(data, f)

希望能有所帮助!

最新更新