【问题标题】:How to read JSON objects from Tweet.py results如何从 Tweet.py 结果中读取 JSON 对象
【发布时间】:2018-04-05 19:07:45
【问题描述】:

我正在尝试读取 Tweet.py 创建的 JSON 文件。但是,无论我尝试什么,我都始终收到 ValueError。

ValueError:期望属性名称:第 1 行第 3 列(字符 2)

JSON 结果格式为:

{ 'Twitter Data' : [ {
"contributors": null, 
"coordinates": null, 
"created_at": "Tue Oct 24 15:55:21 +0000 2017", 
"entities": {
    "hashtags": ["#football"]
   }            
} , {
"contributors": johnny, 
"coordinates": null, 
"created_at": "Tue Oct 24 15:55:21 +0000 2017", 
"entities": {
    "hashtags": ["#football" , "#FCB"]
   }             
} , ... ] }

文件中至少有 50 个这样的 JSON 对象,以逗号分隔。

我读取这个 json 文件的 Python 脚本是:

twitter_data=[]
with open('@account.json' , 'r') as json_data:
    for line in json_data:
        twitter_data.append(json.loads(line))

print twitter_data

Tweet.py 使用以下方式写入这些 Json 对象:

json.dump(status._json,file,sort_keys = True,indent = 4) 

对于如何阅读此文件的任何帮助和指导,我将不胜感激!

谢谢。

【问题讨论】:

  • 能否请您提供一个完整但小得多的示例 JSON 文件?
  • 是的,当然@ChristopherBottoms
  • 1) ' 不是 JSON 中的合法字符串分隔符,2) 您的代码每行都需要一个新的 JSON 文档,但您的示例是一个恰好包含多行的 JSON 文档。

标签: python json twitter tweepy


【解决方案1】:

{ 'Twitter Data' 位应该是 { "Twitter Data" 以及 "Johnny"

也就是说键和值(字符串)必须用双引号括起来。

with open("@account.json","r") as json_data:
    data = json_data.readlines()
    twitter_data.append(json.loads(data))

另外,我自己没有使用过这个,但这也可能会有所帮助:https://jsonlint.com

【讨论】:

  • 我在尝试这个时遇到了以下错误:in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) TypeError: expected string or buffer
【解决方案2】:

首先,正如@Rob 和@silent 所指出的,'Twitter Data' 应该是"Twitter Data"。 Json 需要双引号,而不是单引号来分隔字符串。

其次,当使用json.load()读取时,它需要一个file对象,所以在调用json.load()时,只需传入json_data,它就会将整个json文件读入内存:

with open('@account.json' , 'r') as json_data:
    contents = json.load(json_data)

编辑:

一次处理多个对象:

def get_objs(f):
    content = f.read()

    # Get each object in the contents of the file object.
    # This is kinda clunky and inelegant, but it should work
    objs = ['{}{}'.format(i, '}') for i in content.split('},')]

    # Last json_obj probably got an unnecessary "}" at the end, so trim the
    # last character from it
    objs[-1] = objs[-1][0:-1]

    json_objs = [json.loads(i) for i in objs]
    return json_objs

然后就去吧:

with open('@account.json', 'r') as json_data:
    json_objs = get_objs(json_data)

希望这对您有用。当我在一个类似格式的 json 文件上测试它时,它对我有用。

【讨论】:

  • 我进行了编辑并尝试了。我收到以下错误:ValueError: No JSON object could be decoded
  • 啊,我注意到你说每个都有多个 json 对象。我想出了一个可能的解决方案。立即编辑。
  • @Pythoner1234:您所指的多个对象是列表键Twitter Data 中的“多个”对象,对吧?还是有多个Twitter Data 对象?你能列出 2 或 3 个对象,以便我们清楚 JSON 文件的结构。
  • 尝试此操作时出现以下错误:anaconda/lib/python2.7/json/decoder.py",第 382 行,在 raw_decode raise ValueError("No JSON object could be decoded") ValueError: 没有 JSON 对象可以被解码
  • 您能否提供一个更好的 json 文件示例,如@silent 所问,以便我们更好地了解文件的结构?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-17
  • 2014-01-09
  • 1970-01-01
  • 2018-01-24
相关资源
最近更新 更多