'How to create a multilevel JSON in Python
I'm consuming tweepy in order to get tweets and I want to push them in one JSON file like:
{
"content": [
{
"text": "one tweet",
"rts": 2,
"favs": 17
},
{
"text": "another tweet",
"rts": 2,
"favs": 17
},
{
"text": "one last tweet",
"rts": 2,
"favs": 17
}
]
}
So I use:
import json
json_serial = "tweet"
my_json = {
'content': {
"text": json_serial,
"rt": '2',
"favs": '3',
}
}
print(json.dumps(my_json))
But this would give me one JSON per tweet and I want to know how can I create one JSON and put all the tweets in it.
Solution 1:[1]
I'm not entirely clear on what you're asking, does this help? How are you receiving the tweets, one at a time?
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"}]}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Joel Cormack |
