简体   繁体   中英

extract json data from post body request with python

Is there a way to easily extract the json data portion in the body of a POST request? For example, if someone posts to www.example.com/post with the body of the form with json data, my GAE server will receive the request by calling:

jsonstr = self.request.body

However, when I look at the jsonstr, I get something like :

str: \r\n----------------------------8cf1c255b3bd7f2\r\nContent-Disposition: form-data;
name="Actigraphy"\r\n Content-Type: application/octet-
stream\r\n\r\n{"Data":"AfgCIwHGAkAB4wFYAZkBKgHwAebQBaAD.....

I just want to be able to call a function to extract the json part of the body which starts at the {"Data":...... section.

Is there an easy function I can call to do this?

there is a misunderstanding, the string you show us is not json data, it looks like a POST body. You have to parse the body with something like cgi.parse_multipart . Then you could parse json like answered by aschmid00. But instead of the body, you parse only the data.

Here you can find a working code that shows how to use cgi.FieldStorage for parsing the POST body . This Question is also answered here. .

It depends on how it was encoded on the browser side before submitting, but normally you would get the POST data like this:

jsonstr = self.request.POST["Data"]

If that's not working you might want to give us some info on how "Data" was encoded into the POST data on the client side.

you can try:

import json
values = 'random stuff .... \r\n {"data":{"values":[1,2,3]}} more rnandom things'
json_value = json.loads(values[values.index('{'):values.rindex('}') + 1])
print json_value['data'] # {u'values': [1, 2, 3]}
print json_value['data']['values'] # [1, 2, 3]

but this is and takes a fair amount of assumptions, Im not sure which framework you are using, bottle, flask, theres many, please use the appropriate call to POST to retrieve the values, based on the framework, if indeed you are using one. ,需要大量假设,我不确定您使用的是哪个框架,瓶子,烧瓶,还有很多,请根据框架使用适当的POST调用来检索值,如果确实使用的话一。

I think you mean to do this self.request.get("Data") If you are using the GAE by itself.

https://developers.google.com/appengine/docs/python/tools/webapp/requestclass#Request_get https://developers.google.com/appengine/docs/python/tools/webapp/requestclass#Request_get_all

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