如何在Python中将字典键映射到JSON

时间:2019-04-15 06:27:02

标签: python python-3.x

我正在从Excel工作表中提取数据并将其存储在dictionary变量中,例如:

data = {"customer_name":"XYZ", "customer_mobile":"989898", "customer_country":"country"}

现在我需要调用rest api来创建客户,需要以json的形式发送数据:

{
  "custName": "string",
  "custMobile": "string",
  "custCountry":"string",
}

dictionaryjson中的键是不同的并且不能更改它们中的任何一个,因此如何映射这两个键?

谢谢

4 个答案:

答案 0 :(得分:1)

这有帮助吗?

sonarqube.key and sonarqube.crt

我正在创建一个单独的对象data = {"customer_name":"XYZ", "customer_mobile":"989898", "customer_country":"country"} dataToSend = { "custName" : data["customer_name"], "custMobile": data["customer_mobile"], "custCountry":data["customer_country"], } print(dataToSend) ,并从具有excel工作表中的值的数据对象中填充其值。

谢谢

答案 1 :(得分:1)

您可以对照两个键中的常用值进行检查:

data = {"customer_name":"XYZ", "customer_mobile":"989898", "customer_country":"country"}
api = { "custName": "string", "custMobile": "string", "custCountry":"string",}

for key in data.keys():
    for api_key in api.keys():
        if key[-3:] == api_key[-3:]:
            api[api_key] = data[key]
print(api)

>>> {"custName": "XYZ", "custMobile": "989898", "custCountry":"country"}

检查每个字典中每个键的后3个字符,就可以比较和匹配这些键。

答案 2 :(得分:0)

这是可以帮助您的代码示例。

import json
def convert(word):
    word = word.replace('customer','cust')
    return ''.join(x.capitalize() or '_' for x in word.split('_'))

data = {"customer_name":"XYZ", "customer_mobile":"989898", "customer_country":"country"}

keys = data.keys()
for i in keys:  
  data[convert(i)] = data.pop(i)

r = json.dumps(data)
print (json.loads(r))

答案 3 :(得分:0)

zip()功能用于更改字典的所有键

api=["custName","custMobile","custCountry"]
data=dict(zip(api, list(data.values())))