簡體   English   中英

將JSON對象作為參數插入Python(轉義引號)

[英]Insert JSON object as an argument in Python (Escape the Quote)

我正在嘗試將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調用出錯。 如何轉義此單引號。

如果我錯了,請原諒我,但我認為您對轉換參數字符串類型和解碼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)

如果要使用JSON,請使用Python內置的json模塊。 不要試圖通過將其視為Python字符串數據來解決問題。

import json

然后:

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

然后,如果要將Python數據結構輸出為json:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM