You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python JSON库是否支持从标准输入解析单个JSON值为JSON对象?

Python json库解析多个独立JSON值的实现方法

Python标准库的json模块本身不支持直接批量解析输入中的多个独立JSON值,但可以借助json.JSONDecoder.raw_decode()方法手动实现这个需求,下面是具体方案:

核心思路

json.JSONDecoder.raw_decode()方法可以从字符串的指定位置开始,解析出单个有效JSON值,同时返回解析完成后的索引位置。利用这个特性,我们可以循环遍历输入内容,逐个提取所有独立的JSON值,并存入字典中。

实现代码

import json
import sys

def extract_json_values_to_dict(input_stream):
    decoder = json.JSONDecoder()
    # 读取全部输入内容并去除首尾空白
    input_data = input_stream.read().strip()
    result_dict = {}
    current_index = 0
    value_counter = 1

    while current_index < len(input_data):
        try:
            # 解析单个JSON值,获取值和新的索引位置
            parsed_value, current_index = decoder.raw_decode(input_data, current_index)
            # 将值存入字典,键按顺序命名
            result_dict[f"value_{value_counter}"] = parsed_value
            value_counter += 1
            # 跳过当前值之后的空白字符(空格、换行、制表符等)
            while current_index < len(input_data) and input_data[current_index].isspace():
                current_index += 1
        except json.JSONDecodeError:
            # 遇到无效JSON时停止解析
            break
    return result_dict

if __name__ == "__main__":
    # 从标准输入读取并解析
    final_dict = extract_json_values_to_dict(sys.stdin)
    print(final_dict)

效果验证

针对你提供的示例输入:

"hello" "world" [1,
2] "coding"
"python"

运行上述代码后,会输出如下字典:

{
    "value_1": "hello",
    "value_2": "world",
    "value_3": [1, 2],
    "value_4": "coding",
    "value_5": "python"
}

注意事项

  • 输入中的每个独立值必须是合法的JSON格式(比如字符串需用双引号、数组格式正确等),否则解析会在错误位置终止。
  • 该方法会自动跳过值之间的任意空白字符(空格、换行、制表符等),无需手动预处理输入的格式。

内容的提问来源于stack exchange,提问作者mickey_mac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 15:15:45