python函数将数据转换为JSON

2024-09-26 22:52:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我可以检查一下如何将下面的内容转换成字典吗

代码.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(数据),如下所示

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
}

有没有更好的办法?我不确定,所以我想检查一下


Tags: thetotexttestidmessagestatussat
2条回答

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

  • 无效的转义I\\'m
  • 未经修饰的新线

这些都可以用

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

数据中还有surrogate pairs可能会导致后续问题。这些可以通过执行以下操作来实现fixed

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

在调用json.loads之前

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

d['status'] = 1

Can I check how do we convert the below to a dictionary?

据我所知,data = { }是一个包含变量data内容的字典

I would need to add an additional field called "status" : 1 such that it looks like this

一个简单的更新就可以了

data.update({"status": 1})

相关问题 更多 >

    热门问题