Python:使用json.loads()读取json对象数组 [英] Python: read in an Array of json objects using json.loads()

查看:480
本文介绍了Python:使用json.loads()读取json对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件data.txt,其中包含json对象列表,如下所示:

I have a file data.txt which contains a list of json objects like below:

[{"id":"1111","color":["blue"],"length":"120"},{"id":"1112","color":["red"],"length":"130"},{"id":"1112","color":["yellow"],"length":"136"}]

我尝试使用python json.loads读取它:

I tried to read it using python json.loads:

data = json.loads("data.txt")

,但是随后出现以下错误.我在这里想念什么吗?非常感谢!

but then I got the following errors. Did I miss anything here? Thanks a lot!

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    336             parse_int is None and parse_float is None and
    337             parse_constant is None and object_pairs_hook is None and not kw):
--> 338         return _default_decoder.decode(s)
    339     if cls is None:
    340         cls = JSONDecoder

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.pyc in decode(self, s, _w)
    363 
    364         """
--> 365         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    366         end = _w(s, end).end()
    367         if end != len(s):

/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.pyc in raw_decode(self, s, idx)
    381             obj, end = self.scan_once(s, idx)
    382         except StopIteration:
--> 383             raise ValueError("No JSON object could be decoded")
    384         return obj, end

ValueError: No JSON object could be decoded

推荐答案

您正在尝试读取字符串"data.txt".您想要打开并阅读文件.

You're trying to read the string "data.txt". What you want is to open and read the file.

import json

with open('data.txt', 'r') as data_file:
    json_data = data_file.read()

data = json.loads(json_data)

这篇关于Python:使用json.loads()读取json对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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