我有一根这样的绳子。如何创建一个字典,第一个标记作为键,后面的所有标记作为值
test_string = """###Some Comment
First-tags :
{
"tag1": {
"tagKey1": "tagValue1",
"tagKey2": "tagValue2"
},
"tag2": {
"tagKey1": "tagValue1",
"tagKey2": "tagValue2"
}
so on .....
}
"""
例如: 钥匙将是第一个标签 而价值将是
{
"tag1": {
"tagKey1": "tagValue1",
"tagKey2": "tagValue2"
},
"tag2": {
"tagKey1": "tagValue1",
"tagKey2": "tagValue2"
}
so on .....
}
[编辑:字符串数据在文件中。问题是从文件中读取并创建一个字典,其中键是注释,值是Json数据]
例如,文件将具有:
###Some Comment
First-tags :
{
"tag1": {
"tagKey1": "tagValue1",
"tagKey2": "tagValue2"
},
"tag2": {
"tagKey1": "tagValue1",
"tagKey2": "tagValue2"
}
so on .....
}
###2nd Comment
Second-tags :
{
"tag1": {
"tagKey1": "tagValue1",
"tagKey2": "tagValue2"
},
"tag2": {
"tagKey1": "tagValue1",
"tagKey2": "tagValue2"
}
so on .....
}
###Some other Comment
someother-tags :
{
"tag1": {
"tagKey1": "tagValue1",
"tagKey2": "tagValue2"
},
"tag2": {
"tagKey1": "tagValue1",
"tagKey2": "tagValue2"
}
so on .....
}
您可以使用此正则表达式,它将匹配组1中
:
之前的最后一组单词字符(包括-
),然后将所有其他字符匹配到组2中的下一个注释(###
)或字符串结尾:然后,您可以通过对字符串中的每个匹配项在两个组上进行迭代来创建字典:
输出:
更新
如果您还希望获取注释,可以使用以下代码:
输出:
因此,这里我尝试将字符串转换为JSON
但是为了让它起作用,我的str应该是JSON而不是别的
所以我找到了第一个
{
并从那里获取字符串如果需要,还可以查找JSON的结尾并修剪str(查找
}
)根据问题中的更新更新解决方案更新
相关问题 更多 >
编程相关推荐