If I run print(CURRENT_JSON) then it prints out ChunkName, ChunkId, m and LINE as string, rather than printing out their values. How to fix it?
CURRENT_JSON = '{"ChunkName": "{ChunkName}", "ChunkData": {"ChunkId": "{ChunkId}", "MasterData": [{"Line": "{m}", "LData": "{LINE}"}]} }'
You can't build JSON manually without considering escaping embedded control characters. For instance, what if one of these fields has a " character? Better to build a python dictionary and then serialize it.
import json
CURRENT_JSON = json.dumps({"ChunkName": ChunkName,
"ChunkData": {"ChunkId": ChunkId,
"MasterData": [{"Line": m, "LData": Line}]} })
Related
It is not supposed to be a hard problem, but I've worked on it for almost a day!
I want to create a query which has to be in this format: 'lat':'###','long':'###' where ###s represent latitude and longitude.
I am using the following code to generate the queries:
coordinateslist=[]
for i in range(len(lat)):
coordinateslist.append("'lat':'{}','long':'-{}'".format(lat[i],lon[i]))
coordinateslist
However the result would be some thing similar to this which has "" at the beginning and end of it: "'lat':'40.66','long':'-73.93'"
Ridiculously enough it's impossible to remove the " with either .replace or .strip! and wrapping the terms around repr doesn't solve the issue.
Do you know how I can get rid of those double quotation marks?
P.S. I know that when I print the command the "will not be shown but when i use each element of the array in my query, a " will appear at the end of the query which stops it from working.
directly writing the line like this:
query_params = {'lat':'43.57','long':'-116.56'}
works perfectly fine.
but using either of the codes below will lead to an error.
aa=print(coordinateslist[0])
bb=coordinateslist[0]
query_params = {aa}
query_params = {bb}
query_params = aa
query_params = bb
Try using a dictionary instead, if you don't want to see the " from string representation:
coordinateslist.append({
"lat": lat[i],
"long": "-{}".format(lon[i])
})
It is likely that the error you are getting is something else entirely (i.e. unrelated to the quotes you are seeing in printed outputs). From the format of the query, I would guess that it is expecting a properly formatted URL parameters: reverse_geocode.json?... which 'lat':'41.83','long':'-87.68' is not. Did you try to manually call it with a fixed string, (e.g. using with postman) ?
Assuming you're calling the twitter geo/ API, you might want to ry it out with properly separated URL parameters.
geo/reverse_geocode.json?lat=41.83&long=-87.68
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)
i.e. 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"]))
I have a json object saved inside test_data and I need to know if the string inside test_data['sign_in_info']['package_type'] contains the string "vacation_package" in it. I assumed that in could help but I'm not sure how to use it properly or if it´s correct to use it. This is an example of the json object:
"checkout_details": {
"file_name" : "pnc04",
"test_directory" : "test_pnc04_package_today3_signedout_noinsurance_cc",
"scope": "wdw",
"number_of_adults": "2",
"number_of_children": "0",
"sign_in_info": {
"should_login": false,
**"package_type": "vacation_package"**
},
package type has "vacation_package" in it, but it's not always this way.
For now I´m only saving the data this way:
package_type = test_data['sign_in_info']['package_type']
Now, is it ok to do something like:
p= "vacation_package"
if(p in package_type):
....
Or do I have to use 're' to cut the string and find it that way?
You answer depends on what exactly you expect to get from test_data['sign_in_info']['package_type']. Will 'vacation_package' always be by itself? Then in is fine. Could it be part of a larger string? Then you need to use re.search. It might be safer just to use re.search (and a good opportunity to practice regular expressions).
No need to use re, assuming you are using the json package. Yes, it's okay to do that, but are you trying to see if there is a "package type" listed, or if the package type contains vacation_package, possibly among other things? If not, this might be closer to what you want, as it checks for exact matches:
import json
data = json.load(open('file.json'))
if data['sign_in_info'].get('package_type') == "vacation_package":
pass # do something
Am trying to extract command line arguments passed in python
cmdargs = str(sys.argv)
print cmdargs
it prints
['E:/omation.py', '{"command":"sel_media","value":"5X7_phot
o_paper.png"},{"command":"tray","value":"4X6_photo_paper.png"}']
from this how can i extract command and values .
i dont knoe how to loop this array and get the commnd and value values.plese help
Note: i also want to discard the first value 'E:/omation.py'
You can use Python utils to parse json strings:
import json
examples = json.loads('['+cmdargs[1]+']')
The first import loads json utilities for python. Then, you can parse a json string into a Python dictionary by using json.loads. In the example, I have parsed one of your json strings into a python dictionary. Remember to add '[' and ']' to convert your string to a valid json array. Then, you can get a command and a value like :
print(examples[0]['command'])
print(examples[0]['value' ])
The example you give shows two json objects in the second element of the list cmdargs. Probably the easiest way to capture that case would be to enclose that second argument in square braces, which would make it legal JSON, then loop through the resulting list:
import json
a = json.loads('['+cmdargs[1]+']')
for p in a:
print "command is ", p['command']
print "value is ", p['value']
This is specific to the example you showed, you may need to make it more robust for your purposes.
Your input is not valid JSON. You must find a way to pass the arguments as separate, valid JSON objects. Then you can do this:
# j.py
import json
import sys
print(sys.argv)
for arg in sys.argv[1:]:
j = json.loads(arg)
print(j.get("command"))
print(j.get("value"))
Usage could be:
$ python3 j.py '{"command":"sel_media","value":"5X7_photo_paper.png"}' '{"command":"tray","value":"4X6_photo_paper.png"}'
['j.py', '{"command":"sel_media","value":"5X7_photo_paper.png"}', '{"command":"tray","value":"4X6_photo_paper.png"}']
sel_media
5X7_photo_paper.png
tray
4X6_photo_paper.png
I have below JSON String. Now I want to extract each individual field from that JSON string.
So I decided to create a method parse_json which will accept a variable that I want to extract from the JSON String.
Below is my python script -
#!/usr/bin/python
import json
jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
def parse_json(data):
jj = json.loads(jsonData)
return jj['+data+']
print parse_json('pp')
Now whenever I an passing pp to parse_json method to extract its value from the JSON String, I always get the error as -
return jj['+data+']
KeyError: '+data+'
Any idea how to fix this issue? As I need to pass the variable which I am supposed to extract from the JSON String?
You probably just want this:
return jj[data]
Your code is trying to look up a key named literally '+data+', when instead what you want to do is look up the key with a name of the function's parameter.
Just use data parameter itself.
Replace following line:
return jj['+data+'] # lookup with `+data+`, not `pp`
with:
return jj[data]