Skip to main content
 首页 » 编程设计

python之使用 Python 对 JSON 字符串进行插值替换

2024年12月31日23myhome

配置文件

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 
  } 
}