سؤال

I would like to generate a simple json file from an database.

I am not an expert in parsing json files using python nor NDB database engine nor GQL.

Many thanks for your help

Model Class definition using NDB:

# coding=UTF-8 
from google.appengine.ext import ndb
import logging

class Albums(ndb.Model):
    """Models an individual Event entry with content and date."""

    SingerName = ndb.StringProperty()
    albumName = ndb.StringProperty()

Expected output:

{
"Madonna": ["Madonna Album", "Like a Virgin", "True Blue", "Like a Prayer"],
"Lady Gaga": ["The Fame", "Born This Way"],
"Bruce Dickinson": ["Iron Maiden", "Killers", "The Number of the Beast", "Piece of Mind"]
} 
هل كانت مفيدة؟

المحلول

For consistency, model names should by singular (Album not Albums), and property names should be lowercase_with_underscores:

class Album(ndb.Model):
    singer_name = ndb.StringProperty()
    album_name = ndb.StringProperty()

To generate the JSON as described in your question:

1) Query the Album entities from the datastore:

albums = Album.query().fetch(100)

2) Iterate over them to form a python data structure:

albums_dict = {}
for album in albums:
    if not album.singer_name in albums_dict:
        albums_dict[album.singer_name] = []
    albums_dict[album.singer_name].append(album.album_name)

3) use json.dumps() method to encode to JSON.

albums_json = json.dumps(albums_dict)

Alternatively, you could use the built in to_dict() method:

albums = Album.query().fetch(100)
albums_json = json.dumps([a.to_dict() for a in albums])
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top