Python JSON迭代到POST请求中

时间:2016-05-26 17:48:03

标签: python json rest http-post httprequest

我有一个类似

的JSON文件
{
   "unknown1": 
   [
        {"text": "random text again",
        "time": "Thu May 15 19:21:59 +0000 2016"}, 
        "text": "akmfkdlm safsa fasffalmfa",
        "time": "Thu May 21 09:53:51 +0000 2016"}
   ]
   "unknown2":
   [ 
        "text": "fsda lmfalmfa",
        "time": "Thu May 21 09:53:51 +0000 2016"},
   ]
}

JSON中的第一项是随机(未知)标签,可以有任意数量的这些未知数。在这些未知数内总是有一堆text / time配对。

我正在尝试将每个text发送到我的REST post服务,该服务接受格式为

的JSON
text: "foo bar bat",
mime_type: "text/html",
extract_type: "HP" # HP, MP

所以当我尝试运行我的代码并且不确定该怎么做时,我收到此错误。

这是我的代码:

import json
import requests

with open('locations_stripped.json') as data_file:
    data = json.load(data_file)

headers = {'Content-Type' : 'application/json'}

for thing in data:
    for text, time in data.iteritems():
        print text
        body = [{ "text": text , "mime_type": "text/html", "extract_type": "HP"}]
        r = requests.post('localhost:3003/api/extract/run', data=body, headers=headers)
        print (r.content)

这是错误:

 $ python filterrest.py
unknown1
Traceback (most recent call last):
  File "filterrest.py", line 30, in <module>
    r = requests.post('localhost:3003/api/extract/run', data=body, headers=headers)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 111, in post
return request('post', url, data=data, json=json, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 57, in request
return session.request(method=method, url=url, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 461, in request
prep = self.prepare_request(req)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 394, in prepare_request
hooks=merge_hooks(request.hooks, self.hooks),
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 298, in prepare
self.prepare_body(data, files, json)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 452, in prepare_body
body = self._encode_params(data)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/models.py", line 89, in _encode_params
for k, vs in to_key_val_list(data):
ValueError: too many values to unpack

有一点需要注意的是它是打印错误的文本(“unknown1”而不是“随机文本”),我不知道如何让它只打印文本。

对此有何帮助?

更新

根据每个人的回答/评论我改变了我的代码

... 
for thing in data:
    for text in data[thing]:
        print text['text']

并按照我的预期打印文本['text']。问题在于我在做我的要求的方式。我将我的代码更改为测试并将数据设置为我知道应该工作的内容(我通过Postman运行)。

更改了代码:

r = requests.post('localhost:3003/api/extract/run', data='Hello. Where does the brown fox go?', headers=headers)

预期回应:

[
  {
    "score": 0.30253747367501777,
    "tag": "HP",
  }
]

相反,打印的内容看起来像整个HTML页面。

2 个答案:

答案 0 :(得分:1)

假设你有一个有效的json。您首先需要遍历与“未知”键对应的列表,现在此列表再次包含字典 使用text time个密钥。

for unknown_key in data:
    for obj in data[unknown_key]:
         body = { "text": obj['text'] , "mime_type": "text/html", "extract_type": "HP"}
         r = requests.post('localhost:3003/api/extract/run', data=body, headers=headers)
         print (r.content)

答案 1 :(得分:1)

关于问题的第1部分:

multiple

通过此循环,您无法获得$allowed_filenames = [ 'AGL_001.txt', ]; if(isset($_FILES['upload1']['name'])){ //$errors= array(); $file_name = $_FILES['upload1']['name']; $file_size =$_FILES['upload1']['size']; $file_tmp =$_FILES['upload1']['tmp_name']; $file_type=$_FILES['upload1']['type']; $file_ext=strtolower(end(explode('.',$_FILES['upload1']['name']))); //$img_loc = $file_name.'.'.$file_ext; if (in_array($file_name, $allowed_filenames)) { move_uploaded_file($file_tmp,"uploads/".$file_name); } else { // log an error } } 。您的更新:

for thing in data:
    for text, time in data.iteritems():

是对的。你的text是对的。下一个问题是:

for thing in data:
    for text in data[thing]:
        print text['text']

现在查看模块请求

的文档
  

通常,您希望发送一些表单编码数据 - 非常类似于HTML   形成。为此,只需将字典传递给data参数即可。您的   数据字典将在请求时自动进行表单编码   是

  

有很多时候你想发送不是的数据   形式编码。如果传入字符串而不是dict,则传入该数据   将直接发布。

对于关键字参数headers,您必须提供body = [{ "text": text , "mime_type": "text/html", "extract_type": "HP"}] r = requests.post('localhost:3003/api/extract/run', data=body, headers=headers) 或有效的json data。问题中的变量dict一直是str,而您的更新中的变量是无效的json body。有两种解决方案:

list

或者

str

请求 doc说:

  

您可以直接传递它,而不是自己编码   使用json参数(在版本2.4.2中添加),它将是   自动编码

因此,从版本 2.4.2 开始,最好使用关键字参数body = { "text": text , "mime_type": "text/html", "extract_type": "HP"} # Dont't forget: dict will be used to send form-encoded data # It will work. But not a intended solution for json data r = requests.post('localhost:3003/api/extract/run', data=body, headers=headers) 代替import json body = { "text": text , "mime_type": "text/html", "extract_type": "HP"} r = requests.post('localhost:3003/api/extract/run', data=json.dumps(body), headers=headers) 来发送json数据。所以它是最好的溶剂:

json

<强>综述

我使用这个来源:

data

代码:

body = { "text": text , "mime_type": "text/html", "extract_type": "HP"} 
r = requests.post('localhost:3003/api/extract/run', json=body, headers=headers)
P / S:我不了解你的服务器,所以我无法测试它。我希望,它有效。