python - 如何提取包含在字符串段落之间的 JSON 对象?
问题描述
我有以下字符串:
...some random text...
{
"1":"one",
"2":"two",
"3":{
"31":{
"311":"threeoneone",
"312":"threeonetwo",
"313":"threeonethree"
}
},
"4":{
"41":"fourone",
"42":"fourtwo",
"43":"fourthree"
},
"5":"five",
"6":"six"
}
...some more random text...
如何从中提取 JSON?这就是我想要得到的。
{
"1": "one",
"2": "two",
"3": {
"31": {
"311": "threeoneone",
"312": "threeonetwo",
"313": "threeonethree"
}
},
"4": {
"41": "fourone",
"42": "fourtwo",
"43": "fourthree"
},
"5": "five",
"6": "six"
}
有没有一种 Pythonic 的方式来完成这项工作?
解决方案
在不假设内容的情况下,在具有混合内容的文件中查找 JSON 对象(非 JSON 内容可能包含不成对的大括号,而 JSON 内容可能包含包含不成对大括号的字符串等)的更强大的解决方案是遍历每一次出现{
并遍历}
左括号右侧的每一次出现,并尝试将括号之间的子字符串解析为 JSON:
import json
right_indices = [i for i, c in enumerate(s) if c == '}']
i = 0
while i < len(s) - 1:
if s[i] == '{':
for j in right_indices:
if i < j:
try:
print(json.loads(s[i: j + 1]))
i = j + 1
break
except json.decoder.JSONDecodeError:
pass
i += 1
给定变量中的输入字符串s
,输出:
{'1': 'one', '2': 'two', '3': {'31': {'311': 'threeoneone', '312': 'threeonetwo', '313': 'threeonethree'}}, '4': {'41': 'fourone', '42': 'fourtwo', '43': 'fourthree'}, '5': 'five', '6': 'six'}
推荐阅读
- function - 在地图上循环并使用值上的函数(SCSS)
- html - 带有伪元素的水平居中输入
- mongodb - MongoDb/GeoJson: MultiPolygon vs GeometryCollection containing only polygons
- powerbi - 从 PowerQuery 设置列描述
- java - 如何使用 Swagger 处理 db 对象?
- java - 按字母顺序合并排序名称不起作用
- php - MySql:获取两个具有不同值的随机行
- html - 如何在 Down 处获取 HTML Table 边框
- multithreading - How to set different header for the group thread request in apache jmeter?
- ios - 如何删除未发布的 iOS 应用程序版本