基于Python的JSON字符串插值替换

2024-04-26 01:28:56 发布

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

在配置.ini在

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

在myscript.py在

^{pr2}$

例外情况:

^{3}$

预期产量:

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中。在

有人能帮我吗?有谁能为我的要求提出最好的方法吗?在


Tags: nameiddatarequestordercustomerproductprice
1条回答
网友
1楼 · 发布于 2024-04-26 01:28:56

如果您需要JSON数据,那么您应该在配置中使用JSON-INI格式在这方面是非常有限的,如果您试图在其中填充JSON,可能会有各种各样的工件。在

也就是说,如果使用^{}时唯一的问题是字段插值,则应该使用双大括号(即{{}})来转义大括号,以达到预期效果,即:

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

或者如果您想格式化:

^{pr2}$

屈服:

{
  "order": {
    "order_id": 102,
    "quantity": 315,
    "price": 50
  }
}

相关问题 更多 >