【发布时间】:2021-06-26 16:08:48
【问题描述】:
我可以检查我们如何将以下内容转换为字典吗?
code.py
message = event['Records'][0]['Sns']['Message']
print(message)
# this gives the below and the type is <class 'str'>
{
"created_at":"Sat Jun 26 12:25:21 +0000 2021",
"id":1408763311479345152,
"text":"@test I\'m planning to buy the car today \ud83d\udd25\n\n",
"language":"en",
"author_details":{
"author_id":1384883875822907397,
"author_name":"\u1d04\u0280\u028f\u1d18\u1d1b\u1d0f\u1d04\u1d1c\u0299 x NFTs \ud83d\udc8e",
"author_username":"cryptocurrency_x009",
"author_profile_url":"https://xxxx.com",
"author_created_at":"Wed Apr 21 14:57:11 +0000 2021"
},
"id_displayed":"1",
"counter_emoji":{
}
}
我需要添加名为 "status" : 1 的附加字段,使其看起来像这样:
{
"created_at":"Sat Jun 26 12:25:21 +0000 2021",
"id":1408763311479345152,
"text":"@test I\'m planning to buy the car today \ud83d\udd25\n\n",
"language":"en",
"author_details":{
"author_id":1384883875822907397,
"author_name":"\u1d04\u0280\u028f\u1d18\u1d1b\u1d0f\u1d04\u1d1c\u0299 x NFTs \ud83d\udc8e",
"author_username":"cryptocurrency_x009",
"author_profile_url":"https://xxxx.com",
"author_created_at":"Wed Apr 21 14:57:11 +0000 2021"
},
"id_displayed":"1",
"counter_emoji":{
},
"status": 1
}
想知道最好的方法是什么?
更新:由于某种原因,我设法做到了。
我使用了 ast.literal_eval(data),如下所示。
D2= ast.literal_eval(message)
D2["status"] =1
print(D2)
#This gives the below
{
"created_at":"Sat Jun 26 12:25:21 +0000 2021",
"id":1408763311479345152,
"text":"@test I\'m planning to buy the car today \ud83d\udd25\n\n",
"language":"en",
"author_details":{
"author_id":1384883875822907397,
"author_name":"\u1d04\u0280\u028f\u1d18\u1d1b\u1d0f\u1d04\u1d1c\u0299 x NFTs \ud83d\udc8e",
"author_username":"cryptocurrency_x009",
"author_profile_url":"https://xxxx.com",
"author_created_at":"Wed Apr 21 14:57:11 +0000 2021"
},
"id_displayed":"1",
"counter_emoji":{
},
"status": 1
}
有没有更好的方法来做到这一点?我不确定是否想检查...
【问题讨论】:
-
那已经是是一本字典了。除非您的意思是您有一个 看起来 这样的字符串,在这种情况下,
json.loads就是答案。不要碰ast模块,除非你真的熟悉Python。这些数据是如何进入您的程序的? -
"我也尝试使用 json.loads(data) 但它引发了错误" 什么错误?
-
text值的内容似乎无效 - 这个类 json 是如何创建的? -
这是使用 AWS (SNS) 中的简单通知服务创建的,并将此消息发送到 lambda。放置在 SNS 中的消息是被转换为 JSON 字符串的 JSON 对象(使用 JSON.dumps)。数据正在从 twitter 流式传输。
标签: python json character-encoding surrogate-pairs