简体   繁体   中英

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

I am trying to pass a JSON object as an argument to a python2 script, it works but the final json data has a single quote (') enclosing the object.

Below is my code

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"]

Execution

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

From the above output the final json_data contains quotes in the attribute value 'attributes': ' {apple:newf,mango:newb} ' which is causing error in my GET call. How to escape this single quote. ?

Forgive me if I'm wrong but I think you've got mixed up with converting the argument string type and decoding a json string.

The single quotes in your result means that the entire value is a string.

Firstly the argument you are passing in on the command line isn't valid JSON.

Try starting your program like this:

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

Then later decode the JSON contained in the string like this:

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

ie json.loads and not str.decode

at this point the variable "json_data" isn't holding JSON it's holding a dictionary

You would then have to encode the entire of json_data to pass it in some raw form of http GET unless you have some API doing it for you. Something like

encoded_json_data = json.dumps(json_data)

If you want to work with JSON then use the json module built in to your Python. Don't try to fudge the issue by treating it as Python string data when it isn't.

import json

then:

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

Then if you want to output your Python data structure as json:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM