【问题标题】:Insert JSON object as an argument in Python (Escape the Quote)在 Python 中插入 JSON 对象作为参数(转义引号)
【发布时间】:2018-12-14 03:54:07
【问题描述】:

我正在尝试将 JSON 对象作为参数传递给 python2 脚本,它可以工作,但最终的 json 数据有一个单引号 (') 将对象括起来。

下面是我的代码

import json
import sys
print sys.argv[1]
data_str = sys.argv[1].decode('string-escape')

print data_str
# The above print's fine with no single quotes

json_data= {
    "server-name": "servername",
    "transaction-id": "transaction_id",
    "user-id": "user_id",
    "change-id": "change_id",
    "consumer-name": "consumer_name",
    "platform": "platform",
    "cookbooks": [
        {
            "cookbook-name": "cookbook_name",
            "cookbook-version": "cookbook_version",
            "recipe-name": "receipie_name",
            "attributes": {

            }
        }
                ]
            }
json_data["cookbooks"][0]["attributes"] = data_str.decode('string-escape')

print json_data["cookbooks"]

执行

C:\Python26\python.exe saver.py "{apple:newf,mango:newb}" 
 {apple:newf,mango:newb} 
{apple:newf,mango:newb} 
[{'cookbook-name': 'cookbook_name', 'cookbook-version': 'cookbook_version', 'recipe-name': 'receipie_name', 'attributes': '{apple:newf,mango:newb}'}]

从上面的输出中,最终的 json_data 在属性值中包含引号 'attributes': '{apple:newf,mango:newb}' 导致我的 GET 调用出错。 如何转义这个单引号。 ?

【问题讨论】:

  • 我认为我们不明白你的问题

标签: python json python-2.7 dictionary


【解决方案1】:

如果您想使用 JSON,请使用 Python 中内置的 json 模块。不要试图通过将其视为 Python 字符串数据来掩盖问题。

import json

然后:

json_data["cookbooks"][0]["attributes"] = json.loads(sys.argv[1])

那么如果你想将你的 Python 数据结构输出为 json:

print(json.dumps(json_data["cookbook"]))

【讨论】:

    【解决方案2】:

    如果我错了,请原谅我,但我认为您混淆了转换参数字符串类型和解码 json 字符串。

    结果中的单引号表示整个值是一个字符串。

    首先,您在命令行中传入的参数不是有效的 JSON。

    尝试像这样启动您的程序:

    C:\Python26\python.exe saver.py "{\"apple\":\"newf\",\"mango\":\"newb\"}"
    

    然后像这样解码字符串中包含的 JSON:

    json_data["cookbooks"][0]["attributes"] = json.loads(data_str)
    

    即json.loads 而不是 str.decode

    此时,变量“json_data”没有保存 JSON,而是保存了字典

    然后,您必须对整个 json_data 进行编码,以便以某种原始形式的 http GET 传递它,除非您有一些 API 为您执行此操作。像

    encoded_json_data = json.dumps(json_data)
    

    【讨论】:

      猜你喜欢
      • 2012-11-22
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多