如何在Python中创建多级JSON

2024-05-12 19:48:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用tweepy来获取tweetpy,我想把它们推到一个JSON文件中,比如:

{
  "content": [
    {
      "text": "one tweet",
      "rts": 2,
      "favs": 17
    },
    {
      "text": "another tweet",
      "rts": 2,
      "favs": 17
    },
    {
      "text": "one last tweet",
      "rts": 2,
      "favs": 17
    }
  ]
}

所以我使用:

^{pr2}$

但是这会给我每个tweet一个JSON,我想知道如何创建一个JSON并将所有tweet放入其中。在


Tags: 文件textjsonanothercontentonetweetrts
2条回答

这是你要的。 您需要将tweet数据附加到content变量中,然后,最后您可以将其写入一个文件,其中包含您希望使用它的任何方式。它将生成一个有效的json。在

import json
my_json = {"content": []}

tweets = ["one", "middle", "last"]
for tweet in tweets:
    dict_data = {
        "text": tweet,
        "rt": '2',
        "favs": '3',
    }

    my_json["content"].append(dict_data)
print(json.dumps(my_json,indent=4, sort_keys=True))

输出

^{pr2}$

我不太清楚你在问什么,这有帮助吗? 你是怎么收到这些微博的,一次一条的?在

import json
json_serial = 'tweet'
my_json = { 
    'content': [
        {"text": "tweet one",
        "rt": '1',
        "favs":'3',
        },  
        {"text": "another tweet",
        "rt": '2',
        "favs":'9',
        },  
        {"text": "yet another tweet",
        "rt": '3',
        "favs":'6',
        },  
    ]   
}
print(json.dumps(my_json))


$ python json-python.py 
{"content": [{"rt": "2", "text": "tweet", "favs": "3"}, {"rt": "2", "text": "tweet", "favs": "3"}, {"rt": "2", "text": "tweet", "favs": "3"}]}

相关问题 更多 >