[英]How to convert list of items into json parent-child hierarchy?
I have some items in a list with points, sub-points and sub-sub points need to pass all of them into json in parent-child hierarchy. 我在列表中有一些项目,点,子点和子子点需要将它们全部传递到父子层次结构中的json。
I tried as each point made it to list, if a point consist of point, sub or sub-sub-point all becomes in one list of a point. 我尝试将每个点列入清单,如果由点,子或子子点组成的点都在一个点的列表中。
my list appears like this: 我的列表如下所示:
lst=["1. content","(a) content","(b) ","(i)","(ii"),"(c)","2.","3.","(A)","(B)","4."]
for ptags in soup.findAll('p'):
lst.append(ptags.get_text())
regex = r"^\([a-z]\)\s.*"
regex1=r"^\([\D]+\)\s.*"
j=0
sub = []
for i in lst:
if sub:
match = re.match(regex, i)
match1=re.match(regex1,i)
if match:
sub.append(i)
elif match1:
sub.append(i)
else:
j=j+1
sub = [i]
Notes[str(j)] = sub
else:
if sub:
Notes[str(j)] = sub
sub = [i]
Notes[str(j)] = i
I need the json hierarchy as output in this way :
"1. content",
"(a) content",
"(b) ",
"(i)",
"(ii"),
"(c)",
"2.",
"3.",
"(A)",
"(B)",
"4."
######################################JSON STRUCTURE
[
{
"1. content": [
"(a) content",
{
"(b) ": [
"(i)",
"(ii)"
]
},
"(c)"
]
},
"2.",
{
"3.": [
"(A)",
"(B)"
]
},
"4."
]
If you want to have a similar hierarchy, you should change your data to a dict
. 如果您想拥有类似的层次结构,则应将数据更改为
dict
。 Because you did not include enough information in your code, I just add a sample of what your data should look like: 因为您的代码中没有包含足够的信息,所以我只是添加一个数据样本的示例:
from json import dumps
lst = [{"1. content": ["(a) content", {"(b) ": ["(i)","(ii)"]},"(c)"]},"2.",{"3.": ["(A)","(B)"]},"4."]
Each hierarchy level should be a dictionary. 每个层次结构级别应该是字典。 For elements those have no children, you can pass them as a simple list element.
对于没有子元素的元素,可以将它们作为简单的列表元素传递。
You can get your json string using dumps
now: 您现在可以使用
dumps
获取您的json字符串:
dumps(lst)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.