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"]))
Related
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}]} })
I'm using an API that is giving me and output formatted as
['{"quote":{"symbol":"AAPL"', '"companyName":"Apple Inc."', '"primaryExchange":"Nasdaq Global Select"', '"sector":"Technology"', '"calculationPrice":"close"', '"open":367.88', '"openTime":1593696600532', '"close":364.11', '"closeTime":1593720000277', '"high":370.47', '"low":363.64', '"latestPrice":364.11'}]
...(it keeps going like this with many more categories.)
I am attempting to pull out only the latest price. What would be the best way to do that?
This is what I have but I get a bunch of errors.
string = (data.decode("utf-8"))
data_v = string.split(',')
for word in data_v[latestPrice]:
if word == ["latestPrice"]:
print(word)
print(data_v)
Judging by the output this is JSON. To parse this easily use the JSON module (see https://docs.python.org/3/library/json.html ).
If I'm correct you got this output from Yahoo Finance, if this indeed the case don't fetch and parse it manually but use the yfinance module (see https://pypi.org/project/yfinance/ )
You will have to use JSON module to parse this JSON string. You can convert it into dictionary then. I have indented the JSON code for ease of understanding. You can use the following approach,
import json
text_to_parse = """
{"quote":
{
"symbol":"AAPL",
"companyName":"Apple Inc.",
"primaryExchange":"Nasdaq Global Select",
"sector":"Technology",
"calculationPrice":"close",
"open":367.88,
"openTime":1593696600532,
"close":364.11,
"closeTime":1593720000277,
"high":370.47,
"low":363.64,
"latestPrice":364.11
}
}
"""
parsed_dict = json.loads(text_to_parse)
print(parsed_dict["quote"]["latestPrice"])
When the program is run, it outputs 364.11
One of my responses looks like,
{
"password": [
"Ensure that this field has atleast 5 and atmost 50 characters"
]
}
And I am trying to fetch the string inside password.How I can get it.
Below is the code which I am trying
key = json.loads(response['password'])
print(key[0]),
But it says 'string indices must be integers, not str'
The error message is correct.
key = json.loads(response['password'])
print(key[0]),
The format of json is string. You need to convert the string of a json object to python dict before you can access it.
i.e.: loads(string) before info[key]
key = json.loads(response)['password']
print(key[0])
Usually the json will be a string and you will try and deserialise it into a object graph (which in python are typically are made up of maps and arrays).
so assuming your response is actually a string (eg that was retrieved from a HTTP request/endpoint) then you deserialise it with json.loads (the function is basically load from string), then you've got a map with a 'password' key, that is an array, so grab the first element from it.
import json
resp = '{ "password": [ "Ensure that this field has atleast 5 and atmost 50 characters" ] }'
print json.loads(resp)['password'][0]
I have an output :
result = {
"sip_domains":{
"prefix":[{"name":""}],
"domain":[{"name":"k200.com"},{"name":"Zinga.com"},{"name":"rambo.com"}]
},
"sip_security":{"level":2},
"sip_trusted_hosts":{"host":[]},
"sip_proxy_mode":{"handle_requests":1}
}
from this i just wanted the output to print to my screen :
domain : k200.com
domain : Zinga.com
domain : rambo.com
how can i get this output using regular expression
Help needed urgently
If it's the text you need to parse then Use JSON module to parse the JSON payload:
http://docs.python.org/library/json.html?highlight=json#json
Regular expression are not needed with good programming language like Python.
Otherwise if it's Python dictionary then use Python dictionary [] style item access to read data from the dictionary.
If you are getting this data as a string from somewhere you must convert it to a python dictionary object to access it. You should not have to use any regular expressions to get this output.
import json
# get the json str somehow
json_dict = json.loads(json_str)
for domain_dict in json_dict['sip_domains']['domain']:
print 'domain : %s' % (domain_dict['name'])
I'm trying to use Facebook's REST api, and am encoding a JSON string/dictionary using urllib.urlencode. The result I get however, is different from the correct encoded result (as displayed by pasting the dictionary in the attachment field here http://developers.facebook.com/docs/reference/rest/stream.publish/). I was wondering if anyone could offer any help.
Thanks.
EDIT:
I'm trying to encode the following dictionary:
{"media": [{"type":"flash", "swfsrc":"http://shopperspoll.webfactional.com/media/flashFile.swf", "height": '100', "width": '100', "expanded_width":"160", "expanded_height":"120", "imgsrc":"http://shopperspoll.webfactional.com/media/laptop1.jpg"}]}
This is the encoded string using urllib.urlencode:
"media=%5B%7B%27swfsrc%27%3A+%27http%3A%2F%2Fshopperspoll.webfactional.com%2Fmedia%2FflashFile.swf%27%2C+%27height%27%3A+%27100%27%2C+%27width%27%3A+%27100%27%2C+%27expanded_width%27%3A+%27160%27%2C+%27imgsrc%27%3A+%27http%3A%2F%2Fshopperspoll.webfactional.com%2Fmedia%2Flaptop1.jpg%27%2C+%27expanded_height%27%3A+%27120%27%2C+%27type%27%3A+%27flash%27%7D%5D"
It's not letting me copy the result being thrown out from the facebook rest documentation link, but on copying the above dictionary in the attachment field, the result is different.
urllib.encode isn't meant for urlencoding a single value (as functions of the same name are in many languages), but for encoding a dict of separate values. For example, if I had the dict {"a": 1, "b": 2} it would produce the string "a=1&b=2".
First, you want to encode your dict as JSON.
data = {"media": [{"type":"flash", "swfsrc":"http://shopperspoll.webfactional.com/media/flashFile.swf", "height": '100', "width": '100', "expanded_width":"160", "expanded_height":"120", "imgsrc":"http://shopperspoll.webfactional.com/media/laptop1.jpg"}]}
import json
json_encoded = json.dumps(data)
You can then either use urllib.encode to create a complete query string
import urllib
urllib.encode({"access_token": example, "attachment": json_encoded})
# produces a long string in the form "access_token=...&attachment=..."
or use urllib.quote to just encode your attachment parameter
urllib.quote(json_encoded)
# produces just the part following "&attachment="