简体   繁体   English

Python的json.load怪异行为

[英]Python's json.load weird behavior

I'm trying to extract a specific value from log files in a directory. 我正在尝试从目录中的日志文件中提取特定值。 Now the log files contains JSON data and i want to extract the value for the id field. 现在,日志文件包含JSON数据,我想提取id字段的值。

JSON Data look something like this JSON数据看起来像这样

{
    id: "123",
    name: "foo"
    description: "bar baz" 
}

Code Looks like this 代码看起来像这样

def test_load_json_directly(self):
    with open('source_data/testing123.json') as log_file:
        data = json.load(log_file)
        print data

def test_load_json_from_iteration(self, dir_path, file_ext):
    path_name = os.path.join(dir_path, '*.' + file_ext)

    files = glob.glob(path_name)
    for filename in files:
    with open(filename) as log_file:
        data = json.load(log_file)
        print data

Now I try to call the function test_load_json_directly the JSON string gets loaded correctly. 现在,我尝试直接调用函数test_load_json_directly以正确加载JSON字符串。 No problem there. 没问题。 This is just to check the correct behavior of the json.load function. 这只是为了检查json.load函数的正确行为。

The issue is when I try to call the function test_load_json_from_iteration , the JSON string is not being recognized and returns an error. 问题是当我尝试调用函数test_load_json_from_iteration ,无法识别JSON字符串并返回错误。

ValueError: No JSON object could be decoded

What am I doing wrong here? 我在这里做错了什么?

Your json is invalid. 您的json无效。 The property names and the values must be wrapped with quotes (except if they are numbers). 属性名称和值必须用引号引起来(除非它们是数字)。 You're also missing the commas. 您还缺少逗号。

The most probable reason for this error is an error in a json file. 此错误的最可能原因是json文件中的错误。 Since json module doesn't show detailed errors, you can use the simplejson module to see what's actually happening. 由于json模块没有显示详细的错误,因此您可以使用simplejson模块查看实际发生的情况。

Change your code to: 将您的代码更改为:

import simplejson
.
.
.

data = simplejson.load(log_file)

And look at the error message. 并查看错误消息。 It will show you the line and the column where it fails. 它将向您显示失败的行和列。

Ex: 例如:

simplejson.errors.JSONDecodeError: Expecting value: line 5 column 17 (char 84)

Hope it helps :) Feel free to ask if you have any doubts. 希望对您有所帮助:)随时询问您是否有任何疑问。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM