Python ValueError:无法解码JSON对象 [英] Python ValueError: No JSON object could be decoded

查看:118
本文介绍了Python ValueError:无法解码JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试读取json并获取其值. 我有一个包含JSON档案的文件夹,我需要打开所有档案并从中获取值.

I'm trying to read a json and get its values. I have a folder with the JSON's archives, and I need to open all archives and get the values from them.

这是代码:

# -*- encoding: utf-8 -*-
from pprint import pprint
import json
import os 
def start():
    for dirname, dirnames, filenames in os.walk('test'):
        for filename in filenames:
            json_file = open(os.path.join(dirname, filename)).read()
            # json_file = unicode(json_file, 'utf-8')
            json_data = json.loads(json_file)
           pprint(json_data)
            for key, value in json_data.items():
                print "KEY : ", key
                print "VALUE: ", value
                start()

这是JSON的其中之一

This is one of the JSON's

{ "test" : "Search User 1",
   "url"  : "http://127.0.0.1:8000/api/v1/user/1/?format=json",
   "status_code" : 200,
   "method" : "get"
}

但是当我运行它时,我得到了:

But when I run it, i get this:

ValueError: No JSON object could be decoded

到底是怎么了?昨天它的工作原理与现在完全一样,还是我疯了

What the hell is wrong? Yesterday it was working exactly as it is now, or am I crazy

我尝试过这种方式:

from pprint import pprint
import json
import os
for dirname, dirnames, filenames in os.walk('test'):
    for filename in filenames:
        json_file_contents = open(os.path.join(dirname, filename)).read()
        try:
            json_data = json.loads(json_file_contents)
        except ValueError, e:
            print e
            print "ERROR"

我看不到任何错误'-'

I cant see any error '-'

for filename in filenames:
        with open(os.path.join(dirname,filename)) as fd:
            json_data = fd.read()
            print json_data

这样,我可以看到json文件包含的内容,但不能使用例如json_data['url']

This way I can see what the json files contain, but I can't use for example access by the key, like json_data['url']

推荐答案

.read()方法可能会将光标移动到文件末尾.试试:

It's possible the .read() method is moving the cursor to the end of the file. Try:

for filename in filenames:
    with open(os.path.join(dirname,filename)) as fd:
        json_data = json.load(fd)

看看哪里能找到你.

这当然假定您具有有效的JSON ,如您的示例所示. (请注意结尾的逗号)

This, of course, assumes you have valid JSON, as your example demonstrates. (Look out for trailing commas)

这篇关于Python ValueError:无法解码JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆