首页 > 解决方案 > 如何提取包含在字符串段落之间的 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 的方式来完成这项工作?

标签: python

解决方案


在不假设内容的情况下,在具有混合内容的文件中查找 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'}

推荐阅读