【问题标题】:filter not working in python (json output)过滤器在 python 中不起作用(json 输出)
【发布时间】:2020-05-02 15:24:44
【问题描述】:

我正在尝试在 python 中过滤 json 输出,但无法正常工作。这是我的 json 输出

[ 
        {
            "type": 1
            "name" : "name 1",
            "field" : "aaa",
        }, 
        {
            "type": 2
            "name" : "name 2",
            "field" : "bbb",
        }, 
        {
            "type": 1
            "name" : "name 3"
            "field" : "ccc"
        }, 
]

我想看什么:

[ 
        {
            "field" : "aaa",
        }, 
        {
            "field" : "bbb"
        }, 
        {
            "field" : "ccc"
        }, 
]

这是我的代码,但它不起作用。有人可以帮我看看我做错了什么或错过了什么吗?当我尝试在浏览器中加载 /test 时出现错误 500。

import requests
from flask import Flask, request
import os
import json

app = Flask(__name__)
@app.route('/test')
def Test():
  uri = "https://gitlab.local.com/api/v4/projects/"
  params = {"search":"my_test"}

# Get my_test data from URI
  response = requests.get(uri, params=params)

# Transform json input to python objects
  input_dict = json.loads(response)

# Filter python objects with list comprehensions
  output_dict = [x for x in input_dict if x['field']]

# Transform python object back into json
  output_json = json.dumps(output_dict)

# Show json on browser
  print (output_json)

【问题讨论】:

  • 请给我们一个response 样品
  • input_dict = json.loads(response) 错误有两个原因。首先,response 是一个自定义对象类,但 json 需要一个字符串,因此您可能希望使用 json.loads(response.body) 代替。其次,requests 很棒,所以他们给了你一个捷径来做这件事——只需使用response.json()
  • 另外,您正在打印结果,但您不应该返回它吗?

标签: python json python-3.x filter


【解决方案1】:

鉴于此输入:

input = [ 
    {
        "type": 1,
        "name" : "name 1",
        "field" : "aaa"
    }, 
    {
        "type": 2,
        "name" : "name 2",
        "field" : "bbb"
    }, 
    {
        "type": 1,
        "name" : "name 3",
        "field" : "ccc"
    }
]

这个:

output = [x['field'] for x in input]

返回这个:

[u'aaa', u'bbb', u'ccc']

如果你想要一个字典列表:

output = [{'field': x['field']} for x in input]

【讨论】:

  • 他想要一个字典列表,而不是字符串列表。 [{'field': x['field']} for x in input] 怎么样?
  • @JohnGordon 谢谢约翰,添加了。
【解决方案2】:

感谢您的帮助。

我尝试了这些建议,但没有奏效。我不断收到以下错误消息:

2020-01-16T10:37:33.440-03:00 [APP/PROC/WEB/0] [ERR] TypeError: the JSON object must be str, bytes or bytearray, not Response
2020-01-16T10:37:33.440-03:00 [APP/PROC/WEB/0] [ERR] raise TypeError(f'the JSON object must be str, bytes or bytearray,

'

幸运的是,我可以用下面的代码解决这个问题:

import requests
from flask import Flask, request
import os
import json

app = Flask(__name__)
@app.route('/test')
def Test():
  uri = "https://gitlab.local.com/api/v4/projects/"
  params = {"search":"my_test"}

  response = requests.get(uri, params=params).content
  data = json.loads(response)
  paragraph = "id: " + str(data[0]["id"]) + "; Description: " + data[0]["description"] + "; path: " + data[0]["path"]
  return({"Test" : paragraph})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-17
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 2016-03-03
    • 2017-04-04
    • 2011-05-24
    • 2015-11-26
    相关资源
    最近更新 更多