我正在开发一个简单的网络应用程序,用于从新闻文章api中提取查询信息。我希望通过在我的烧瓶服务器中剥离不必要信息的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.response.docs。我尝试返回response.response.docs
,但我发现这是不正确的。
b)我的最后四行似乎是多余的,我想知道如何将我的回归放在我的第一个开放区块内。我试了'w+'
和'r+'
没有运气。
答案 0 :(得分:0)
我不确定我是否完全得到你的问题,但听起来你想做的是:
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的jsonify函数
重新序列化并轻松将其发送到客户端希望有所帮助