将字符串添加到字典中而不带引号的python

时间:2018-10-29 19:11:04

标签: python dictionary variables

我正在使用json数据发布到API。 我一切都按预期方式格式化数据。但是,当我将其放在一起时,在变量周围得到了意外的单引号。 我的字典如下。

                    data = {  
           "Items": [
           out2
           ],
           "TenantToken": "user",                 
           "UserToken": "pass"                    
                }

“ out2”中的数据类似。

{"Code": "123456789", "LocationCode": "OTV-01", "Quantity": 69, "WarehouseId": 6884}, {"Code": "123456789", "LocationCode": "OTV-01", "Quantity": 123, "WarehouseId": 6884},

但是,当我发布数据时,

{'Items': ['{"Code": "805619531972", "LocationCode": "OSWATV-01", "Quantity": 126, "WarehouseId": 6884}, {"Code": "805619531989", "LocationCode": "OSWATV-01", "Quantity": 142, "WarehouseId": 6884}'], 'TenantToken': 'user', 'UserToken': 'pass'}

添加单引号

['{ }'] 

代替

[{ }]

这是我在这里的第一篇文章,因此,如果我错过任何内容,我深表歉意。 谢谢!

编辑:out2当前是一个使用熊猫创建并导出到.txt的字符串(其保存以供将来使用,因为我将循环多个文件) 我已经使用

导入了它
text_file = open('file.txt', "r")
                lines = text_file.readlines()

目标是使要发送的json看起来像这样。

   {
  "Items": [
    {
      "Code": "String",
      "LocationCode": "String",
      "Quantity": 0,
      "WarehouseId": 0
    },
    {
      "Code": "String",
      "LocationCode": "String",
      "Quantity": 0,
      "WarehouseId": 0
    }
  ],
  "TenantToken": "String",
  "UserToken": "String"
}

1 个答案:

答案 0 :(得分:1)

使用ast将字符串转换为字典。然后删除您在“ Items”之后使用的多余列表:最后使用json.dumps生成有效的json输出。

import json
import ast

out2 = '{"Code": "123456789", "LocationCode": "OTV-01", "Quantity": 69, "WarehouseId": 6884}, {"Code": "123456789", "LocationCode": "OTV-01", "Quantity": 123, "WarehouseId": 6884}'

data = {
    "Items":
        ast.literal_eval(out2),
    "TenantToken": "user",
    "UserToken": "pass"
}

print(json.dumps(data))

输出

{"Items": [{"Code": "123456789", "LocationCode": "OTV-01", "Quantity": 69, "WarehouseId": 6884}, {"Code": "123456789", "LocationCode": "OTV-01", "Quantity": 123, "WarehouseId": 6884}], "TenantToken": "user", "UserToken": "pass"}