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

标签 python json python-3.x

配置文件

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/

相关文章:

python - 为什么退出窗口按钮有效,但游戏中的退出按钮不起作用?

Python REST API 发布列表

php - 需要将 MySQL 记录转换为 JSON 树

php - MySQL JSON 字符串与 PHP。修复逗号

python - 是否可以运行列表中的命令?

python - 在存储在谷歌驱动器中的谷歌 Colaboratory 中导入 zip 文件

python - 使用 Python 将 Excel 转换为 JSON

python - 获取请求参数并在forms.py中作为widget参数使用

python - 如何区分文件之类的对象和文件之类的路径

python - 在 SQLAlchemy 中定义表时,如何将函数(依赖于其他列的表达式)定义为列的默认值?