I have a json object in the form of a dictionary that i make outside of a function. I make a baseline for what the data inside the json object and its keys. What i am trying to do is to save the data i have collected in the function to the json object. I am very unsure on how i add that new data to the json data without overwriting any existing data already present in the json object.
Something i have tried to do is load the json object i am trying to update by doing:
import json
data = json.loads(json_obj)
However, when i do this, it throws me an error when assigning new data to it.
TypeError: the JSON object must be str, bytes or bytearray, not dict
This is the json object from before.
{
"text": "test text",
"created_at": "some date",
"entity": "most_common_entity",
"username": "someuser",
"tweet_id": "coolid",
"hashtags": "#coolndat"
}
And the way i am attempting to add data to it is by doing:
json_obj["text"] = row["text"]
json_obj["created_at"] = row["created_at"]
json_obj["entity"] = most_common_entity
json_obj["username"] = row["username"]
json_obj["tweets_id"] = row["id"]
json_obj["hashtags"] = row["hashtags"]
It would be amazing if anyone would be able to help my solve my problem.
The end goal would be for the json object to look something like this:
{
{
"text": "test text",
"created_at": "some date",
"entity": "most_common_entity",
"username": "someuser",
"tweet_id": "coolid",
"hashtags": "#coolndat"
},
{
"text": "Text two",
"created_at": "12/5/3042",
"entity": "ORG",
"username": "cooluser3",
"tweet_id": "nice",
"hashtags": "#verysickhashtag"
}
}
CodePudding user response:
The result that you expect to get is a set type, not a dict. Here is an example how you could do that using list.
In [7]: not_a_json_just_a_python_dict = {
...: "text": "test text",
...: "created_at": "some date",
...: "entity": "most_common_entity",
...: "username": "someuser",
...: "tweet_id": "coolid",
...: "hashtags": "#coolndat"
...: }
In [8]: list_of_dicts = [not_a_json_just_a_python_dict]
In [9]: list_of_dicts.append({
...: "text": "test text",
...: "created_at": "some date",
...: "entity": "most_common_entity",
...: "username": "someuser",
...: "tweet_id": "coolid",
...: "hashtags": "#coolndat"
...: })
In [10]: list_of_dicts
Out[10]:
[{'text': 'test text',
'created_at': 'some date',
'entity': 'most_common_entity',
'username': 'someuser',
'tweet_id': 'coolid',
'hashtags': '#coolndat'},
{'text': 'test text',
'created_at': 'some date',
'entity': 'most_common_entity',
'username': 'someuser',
'tweet_id': 'coolid',
'hashtags': '#coolndat'}]