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

json.loads加载JSON数组后遍历出现字符逐个输出问题求助

Why is my JSON array being iterated as individual characters?

Ah, I see the issue here—you're accidentally turning your JSON array into a string literal, which is why iterating over it gives individual characters instead of the objects you expect. Let's break this down:

The Root Cause

Look at this line in your code:

obj = json.loads("\"" + line[11:-7] + "\"")

You're wrapping the truncated line[11:-7] content in extra double quotes. Let's say line[11:-7] is already a valid JSON array string like this:

[{"ip":"66.102.8.203","sg_user_id":7018833,...}]

By adding those surrounding quotes, you're turning it into a string literal instead of a JSON array:

"[{"ip":"66.102.8.203","sg_user_id":7018833,...}]"

When json.loads() parses this, it returns a single string (not a list). So when you loop over obj, you're iterating over each character in that string—hence the broken output you're seeing.

The Fix

Simply remove the manual surrounding quotes and parse the truncated line directly:

with open(filtered_aws_logs_path) as input:
    for i, line in enumerate(input):
        obj = json.loads(line[11:-7])  # No extra quotes here
        print("response: " + str(i))
        print(obj)
        for json_item in obj:
            print(json_item)
        break

Quick Verification

If you add print(type(obj)) before your loop:

  • Before the fix: It will output <class 'str'> (confirming it's a string)
  • After the fix: It will output <class 'list'> (confirming it's the JSON array you expected)

Now when you iterate over obj, you'll get each dictionary in the array instead of individual characters.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 03:57:55