【问题标题】:Django - Create a JSON like thatDjango - 创建一个这样的 JSON
【发布时间】:2013-07-15 12:51:28
【问题描述】:

我正在使用 Django 1.5.1 - Postgresql 9.1

我有这样的数据库表,

1.column(id) : [1] [2]
2.column(name)  [josh] [ashley]
3.column(childrens) [david , 8 ; joe , 5] [suzie , 13 ; jennifer , 6]

数据库表示例图-->http://s9.postimg.org/4kttacbxr/db_example.png

我想创建一个这样的 JSON 文件:

    [{
        id:1,
        name:'josh',
        children : [{
            name:'david',
            age:8
        }, {
            name:'joe',
            age:5
        }]
    },{
        id:2,
        name:'ashley',
        children:[{
            name:'suzie',
            age:13
        }, {
            name:'jennifer',
            age:6
        }]
    }]

我该怎么做?

【问题讨论】:

  • 只需遍历结果集并创建 Python listdicts,然后使用 json.dumps
  • 对于“就是这样”JSON,我想你想要JSON-nevins

标签: django json django-models


【解决方案1】:

最好的解决方案是 @Paulo 建议的。遍历结果集,将所需项目放入字典,然后使用 json.dump 对结果进行 json-ify。

类似这样的:

d = dict()
i = 0
for result in resultset:
    i = i+1
    r = dict()
    r['name'] = result.name
    r['age'] = result.age
    r['height'] = result.height
    d[str(i)] = r
_json = json.dumps(d)

【讨论】:

  • 我是 Django 新手。我会试试。 (感谢你们俩的快速回答)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-21
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 2011-10-04
  • 2011-08-10
相关资源
最近更新 更多