How do I make string like "payload={'key':'value'...}" to become a variable payload with value assigned to it "{'key':'value'...}"? Thanks.
Like they said on github, use a query string parser, like this:
import urlparse
str = "payload={'key':'value'}"
print urlparse.parse_qs(str)
Result is this:
{'payload': ["{'key':'value'}"]}
payload = json.loads(jsonstring)
payload = pickle.loads(pickstring)
Don't pickle untrusted data.
Related
Url : 127.0.0.1:5000/mywebservice?&list=hello&list=world&dict={"type":"mail","subject":"Hello","content":"hello world"}
I am trying to get json from the url
list=request.args.getlist(list) allow me to get list like this way list[0] =hello ,list[1] =world
the URL will be like that:
Url : 127.0.0.1:5000/mywebservice&list=hello&list=world&dict[type]=mail&dict[subject]=Hello&dic[content]=hello world
Is there a way that allows me to get the dictionary like this way?
Expected result:
dic=request.args.get(dict)
var= dic['type']
print(var)====> mail
however:
dic = request.args.get(dict)
var = dic['type']
print(var) : Exception
PS: request.json doesn't have access to the url and there is not
dic = request.args.getjson(dict)
If I understood correctly dict from URL will have serialized JSON. You need to use json package to de-serialize it.
import json
url_dict = request.args.get('dict')
dic = json.loads(url_dict)
print (dic['type'])
I got some data from an API with requests:
r = requests.get(...)
a = r.text
print(type(a))
str2JSON = json.dumps(a,indent=4)
print(type(str2JSON))
The result is:
class 'str'
class 'str'
Then I try loads instead of dumps:
str2JSON_2 = json.loads(a)
print(type(str2JSON_2))
And I get class list!!!
Why is that behaviour?
If you dump a string into JSON and you don’t get an error, does it automatically mean that the JSON is well parsed? Shouldn't that be a JSON class?
The thing you get back from requests is a str value containing a JSON encoded value.
dumps takes that str and produces another string containing the JSON-encoded version of the original (JSON-encoded) string.
You need loads to decode the string into a value.
json2str = json.loads(a,indent=4) # name change to reflect the direction of the operation
Consider:
>>> s = '"foo"' # A JSON string value
>>> json.dumps(s)
'"\\"foo\\""'
>>> json.loads(s)
'foo'
The string may, of course, encode a value other than a simple string:
>>> json.loads('3') # Compare to json.loads('"3"') returning '3'
3
>>> json.loads('[1,2,3]')
[1,2,3]
>>> json.loads('{"foo": 6}')
{'foo': 6}
requests, though, doesn't actually require you to remember which direction dumps and loads go (although you should make it a point to learn). A Response object has a json method which decodes the text attribute for you.
json2str = r.json() # equivalent to json2str = json.loads(r.text)
you are using requests. it provides convince method to parse your response as json (i.e. it loads it for you) you want a = r.json(). This way a would be JSON object and you can dump it as string later on. That is assuming you get valid json as response.
here is an example
import requests
import json
url = 'https://reqres.in/api/users' # dummy resposnse
resp = requests.get(url)
my_json = resp.json()
#print example user
print(my_json['data'][0])
json_string = json.dumps(my_json, indent=4)
print(json_string)
json.dumps returns a JSON formatted python string object.
Below the is the statement you can notice in actual implementation file for def dumps
"""Serialize obj to a JSON formatted str.
Here is the link im opening in python:
response = urllib.request.urlopen('http://freegeoip.net/json/1.2.3.4').read()
print(response)
After printing the response it gives the result:
b'{"ip":"1.2.3.4","country_code":"US","country_name":"United States","region_code":"WA","region_name":"Washington","city":"Mukilteo","zip_code":"98275","time_zone":"America/Los_Angeles","latitude":47.913,"longitude":-122.305,"metro_code":819}\n'
My question is, how can i print just the region name? i have this code so far:
import json
import urllib.request
response = urllib.request.urlopen('http://freegeoip.net/json/1.2.3.4').read()
print(response)
result = json.loads(response.decode('utf8'))
Its the last bit of pulling out the specific piece of data im stuck on. Thanks in advance!
Your result object returned from json.loads will be a dictionary, so you can print the value like so:
print result['region_name']
Or even better, a bit more defensively, in the event that key doesn't exist:
print result.get('region_name', 'No region specified')
Also note that your urllib call should be:
response = urllib.urlopen('http://freegeoip.net/json/1.2.3.4').read()
At this point, you'd be able to access it as you would a python object:
result['region_code']
you can use ast.literal_eval:
>>> import ast
>>> my_dict = ast.literal_eval(response.strip())
>>> my_dict['region_name']
'Washington'
given json {"foo":"bazz","1":2}
I want to convert it to POST data :
"foo"="bazz";"1"=2;
(the data format in case it were posted from html form)
is there any exist decoder for json>> POST data? if no, does next script will do it as well?
json_body = {"foo":"bazz","1":2}
data = ''
for key, value in json_body.items():
data += '"{key}"={value};'.format(key=key, value=value)
print data
>> "foo"="bazz";"1"=2;
thanks
Use urllib.parse.urlencode:
from urllib.parse import urlencode
data = urlencode(json_body)
This produces x-www-form-urlencoded data, which is the default mime-type used by browsers when POST-ing HTML forms.
I have a python as CGI and the POST from jquery will transform json object to array, so when I see the POST from jquery, I actually see:
login_user[username]=dfdsfdsf&login_user[password]=dsfsdf
(the [ and ] already escaped)
My question is how I can convert this string back to JSON in python? Or, how can I convert this string to python array/dict structure so that I can process it easier?
[edit]
My jquery is posting:
{'login_user': {'username':username, 'password':password}}
If what you want to accomplish is to send structured data from the browser and then unpack it in your Python backend and keep the same structure, I suggest the following:
Create JavaScript objects in the browser to hold your data:
var d = {}
d['login_user'] = { 'username': 'foo', 'password': 'bar' }
Serialize to JSON, with https://github.com/douglascrockford/JSON-js
POST to your backend doing something like this:
$.post(url, {'data': encoded_json_data}, ...)
In your Python code, parse the JSON, POST in my example is where you get your POST data in your CGI script:
data = json.loads(POST['data'])
data['login_user']
import re
thestring = "login_user[username]=dfdsfdsf&login_user[password]=dafef"
pattern = re.compile(r'^login_user\[username\]=(.*)&login_user\[password\]=(.*)')
match = pattern.search(thestring)
print match.groups()
Output:
>>> ('dfdsfdsf', 'dafef')
Thus,
lp = match.groups()
print "{'login_user': {'username':"+lp[0]+", 'password':"+lp[1]+"}}"
shall bear: >>> {'login_user': {'username':dfdsfdsf, 'password':dafef}}
>>> import json
>>> data = {'login_user':{'username':'dfdsfdsf', 'password':'dsfsdf'}}
>>> json.dumps(data)
'{"login_user": {"username": "dfdsfdsf", "password": "dsfsdf"}}'
I suspect that data would already be contained in a GET var if that's coming from the URL...