0

我可以检查我们如何将以下内容转换为字典吗?

代码.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
}

有没有更好的方法来做到这一点?我不确定所以想检查...

4

2 回答 2

1

我可以检查我们如何将以下内容转换为字典吗?

据我所知,将data = { }包含内容的字典分配给变量data

我需要添加一个名为"status" : 1这样的附加字段,它看起来像这样

一个简单的更新应该可以解决问题。

data.update({"status": 1})
于 2021-06-26T16:22:31.937 回答
0

我在尝试将字符串反序列化为 JSON 时发现了两个问题

  • 无效转义I\\'m
  • 未转义的换行符

这些可以解决

data = data.replace("\\'", "'")
data = re.sub('\n\n"', '\\\\n\\\\n"', data, re.MULTILINE)
d = json.loads(data)

数据中还有可能导致问题的代理对。这些可以通过做来解决

data = data.encode('utf-16', 'surrogatepass').decode('utf-16')

打电话之前json.loads

将数据反序列化为 a 后dict,您可以插入新的键/值对。

d['status'] = 1
于 2021-06-26T17:03:19.567 回答