【发布时间】:2015-07-20 04:27:15
【问题描述】:
我有一个像这样的大型 JSON 文件:
{
"data" : [
{"album": "I Look to You", "writer": "Leon Russell", "artist": "Whitney Houston", "year": "2009", "title": "\"A Song for You\""},
{"album": "Michael Zager Band", "writer": "Michael Zager", "artist": "Whitney Houston", "year": "1983", "title": "\"Life's a Party\""},
{"album": "Paul Jabara & Friends", "writer": "Paul Jabara", "artist": "Whitney Houston", "year": "1978", "title": "\"Eternal Love\""},
...
...我正在尝试制作一个非常简单的 API 来获取不同的值。现在我可以很容易地获得localhost/data/1/title,例如获得第一个标题值,但我想通过localhost/titles 或其他方式获得所有的标题。我将如何修改此处的 do_GET 方法以添加此类功能?
def do_GET(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
path = self.path[1:]
components = string.split(path, '/')
node = content
for component in components:
if len(component) == 0 or component == "favicon.ico":
continue
if type(node) == dict:
node = node[component]
elif type(node) == list:
node = node[int(component)]
self.wfile.write(json.dumps(node))
return
【问题讨论】:
-
你试过python的json模块了吗? docs.python.org/2/library/json.html 这可能会有所帮助。
-
@HaochenWu,我想她已经在使用那个模块了。
-
哦,我明白了。您的代码中有转储。那么loads函数有什么问题呢?它应该返回一个包含 json 文件中所有结构的对象。你可以从那开始,它应该很容易迭代。抱歉,我可能仍然没有在这里得到您的问题。
-
您的 do_GET 函数似乎是一些 Web 应用程序,但如果没有更多上下文,很难看出它的作用。
标签: python json dictionary list-comprehension