【问题标题】:Error while appending collected tweets to a list将收集的推文附加到列表时出错
【发布时间】:2021-02-25 05:54:50
【问题描述】:

试图将收集到的推文内容存储到数据列表中。 但是遇到错误我不知道如何解决。

代码:

data=[]

import json

def string_to_json(line):
    import ast
    jsonval=ast.literal_eval(line)
    return jsonval

with open('tweetFile.json', encoding = 'utf-8') as f1:
    for line in f1:
        line=string_to_json(line)
        print(line['full_text'])
        data.append(json.loads(line))

错误:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-30-5e3ff09bab03> in <module>
     10         line=string_to_json(line)
     11         print(line['full_text'])
---> 12         data.append(json.loads(line))

~\anaconda3\lib\json\__init__.py in loads(s, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    339     else:
    340         if not isinstance(s, (bytes, bytearray)):
--> 341             raise TypeError(f'the JSON object must be str, bytes or bytearray, '
    342                             f'not {s.__class__.__name__}')
    343         s = s.decode(detect_encoding(s), 'surrogatepass')

TypeError: the JSON object must be str, bytes or bytearray, not dict

【问题讨论】:

    标签: python json twitter tweepy


    【解决方案1】:

    json.loads()可以直接加载字符串:

    data=[]
    import json
    
    with open('tweetFile.json', encoding = 'utf-8') as f1:
        for line in f1:
            #print(line['full_text'])
            data.append(json.loads(line))
    

    【讨论】:

    • 问题是由于某种原因它不起作用。我收到此错误:JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
    猜你喜欢
    • 1970-01-01
    • 2017-05-30
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    • 2011-02-20
    相关资源
    最近更新 更多