配置文件
request = {"order": {"order_id": {order_id},"customer_id":10001, "prd_price":50, "quantity":{quantity}, "total_price": {total_price}, "product_id":1, "last_name": "lavanya"}}
data = {'quantity': '315', 'total_price': '50', 'order_id': '102'}
我的脚本.py
req = config[reflowStep]['request']
req = req.format(**data)
异常(exception):
Traceback (most recent call last):
File "myscript.py", line 247, in reflow
req = req.format(**data)
KeyError: '"order"'
预期输出:
req = {
"order":{
"order_id":102,
"customer_id":10001,
"prd_price":50,
"quantity":315,
"total_price":50,
"product_id":1,
"last_name":"lavanya"
}
}
如果我作为字符串传递(不带“{/}”),它就可以工作。 例如:
request = "order_id": {order_id},"customer_id":10001, "prd_price":50, "quantity":{quantity}, "total_price": {total_price}, "product_id":1, "last_name": "lavanya"
但我的要求是我需要在运行时将值填充到 json 中。
任何人,可以帮助我吗?谁能建议我的要求的最佳方法?
最佳答案
如果您需要 JSON 数据,您真的应该为您的配置使用 JSON - INI 格式在这方面非常有限,如果您尝试在其中填充 JSON,可能会有各种工件。
也就是说,如果您在使用 str.format()
时唯一的问题是场插值您应该使用双大括号(即 {{
和 }}
)转义您的花括号以达到预期的效果,即:
request = '{{"order": {{"order_id": {order_id}, "quantity":{quantity}, "price": {price}}}}}'
data = {'quantity': '315', 'price': '50', 'order_id': '102'}
print(request.format(**data))
# {"order": {"order_id": 102, "quantity":315, "price": 50}}
或者如果你想格式化:
print(json.dumps(json.loads(request.format(**data)), indent=2))
产量:
{
"order": {
"order_id": 102,
"quantity": 315,
"price": 50
}
}
关于python - 使用 Python 对 JSON 字符串进行插值替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52588109/