JSON:在python中剥离不必要信息的文件

JSON:在python中剥离不必要信息的文件,python,json,flask,Python,Json,Flask,我正在开发一个简单的web应用程序,它从新闻文章api中提取查询信息。我希望通过剥离flask服务器中json文件中不必要的信息来减少客户端处理。我想将编辑后的json存储在数据库中(目前仅在下面的代码中本地存储) 目前,我的python代码如下所示: def get_query(query): response = urllib2.urlopen(link + '?q=' + query + '&fl=' + fields + '&api-key=' + key)

我正在开发一个简单的web应用程序,它从新闻文章api中提取查询信息。我希望通过剥离flask服务器中json文件中不必要的信息来减少客户端处理。我想将编辑后的json存储在数据库中(目前仅在下面的代码中本地存储)

目前,我的python代码如下所示:

def get_query(query):
    response = urllib2.urlopen(link + '?q=' + query + '&fl=' + fields + '&api-key=' + key)
    result = response.read()
    # store json locally 
    with open('static/json/' + query + '.json', 'w') as stored_json:
      json.dump(result, stored_json)
    with open('static/json/' + query + '.json', 'r') as stored_json:    
      return json.load(stored_json)
我的问题是:

a)我不确定如何正确编辑json。目前在我的javascript中,我在ajax调用中使用的数据如下:

data.response.docs[i].headline.main;
我更愿意将对象文档作为json存储并返回。我知道python代码中的变量result是字符串,所以我无法编写并返回result.response.docs。我试图返回
response.response.docs
,但我意识到这是不正确的


b)我的最后四行似乎是多余的,我想知道如何将我的回报放在我的第一个开放区块内。我尝试了
'w+'
'r+'
,但运气不佳。

我不确定我是否完全理解了你的问题,但听起来你想做的是:

1) receive the response
2) parse the json into a Python object
3) filter the data
4) store the filtered data locally (in a database, file, etc)
5) return the filtered data to the client
我假设您的json.dump/json.load组合旨在将json字符串转换为您可以轻松操作的格式(即Python对象)。如果是这样,json.loads(重点放在s上)会满足您的需要。试着这样做:

import json

def get_query(query):
    response = urllib2.urlopen(...)
    result = json.loads(response.read())

    # result is a regular Python object holding the data from the json response

    filtered = filter_the_data(result)

    # filter_the_data is some function that manipulates data

    with open('outfile.json', 'w') as outfile:
        # here dump (no s) is used to serialize the data
        # back to json and store it on the filesystem as outfile.json
        json.dump(filtered, outfile)

    ...
此时,您已经将数据保存在本地,并且仍然保留对已过滤数据的引用。您可以使用Flask的函数重新序列化它并将其发送到客户端

希望能有帮助