【问题标题】:Extracting Json Objects from string从字符串中提取 Json 对象
【发布时间】:2020-06-18 00:47:46
【问题描述】:

假设我有一个传入的字符串 oversocket,它看起来像这样

'text.....text {"foo": {"bar":100}} text {"bar":2} test {"foo"'

从传入字符串中仅提取 json 对象的最佳方法/库是什么?

我已经尝试过 simplejson 库中的 simplejson.JSONDecoder。但是,它不仅仅是寻找对象,或者我不知道如何使用它。

到目前为止,我已经尝试过这样的事情

import simplejson as json
input_buffer = ""
def in_data(data):
    input_buffer += data
    try:
        dict, idx = json.JSONDecoder().raw_decode(input_buffer)
    except:
        #handle exception in case nothing found 
    self.handle_input(dict) #send the dictionary for processing
    input_buffer = input_buffer[idx:]

【问题讨论】:

  • 到目前为止您尝试过什么?显示一些代码。

标签: python json python-3.x simplejson


【解决方案1】:

纯 Python 解决方案,基于简单的括号计数和 trying 来解析收集的文本。

import json

inp = list(r'text {"foo": {"bar":100}} text {"bar":2} test ')
stack = ''
bracket_counter = 0
jsons = []

while inp:
    char = inp.pop(0)
    if char == '{':
        bracket_counter += 1

    if bracket_counter:
        stack += char

    if char == '}':
        bracket_counter -= 1
        if bracket_counter == 0:
            try:
                parsed = json.loads(stack)
                jsons.append(parsed)
            except json.JSONDecodeError:
                pass
            stack = ''

print(jsons)  # -> [{'foo': {'bar': 100}}, {'bar': 2}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    相关资源
    最近更新 更多