如何在不覆盖现有数据的情况下向已经存在的json对象添加数据



我有一个json对象在字典的形式,我使一个函数之外。我为json对象及其键中的数据做了一个基线。我要做的是将我在函数中收集的数据保存到json对象。我非常不确定如何在不覆盖json对象中已经存在的任何现有数据的情况下将新数据添加到json数据。

我试图做的事情是加载json对象,我试图通过做更新:

import json
data = json.loads(json_obj)

但是,当我这样做时,它会在给它分配新数据时抛出错误。

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

这是前面的json对象。

{
"text": "test text",
"created_at": "some date",
"entity": "most_common_entity",
"username": "someuser",
"tweet_id": "coolid",
"hashtags": "#coolndat"
}

我试图添加数据到它的方式是这样做:


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"]

如果有人能帮我解决我的问题,那将是令人惊奇的。

最终目标是让json对象看起来像这样:
{
{
"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"
}
}

期望得到的结果是一个集合类型,而不是一个字典。下面是一个使用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'}]

最新更新