Parsing data to create a json data object with Python

后端 未结 3 1885
甜味超标
甜味超标 2020-12-11 04:26

Here is my data from google bigquery to parse:

{
    u\'kind\': u\'bigquery#queryResponse\',
    u\'rows\': [
        {
            u\'f\': [
                        


        
3条回答
  •  庸人自扰
    2020-12-11 04:59

    Version 0.28.0 and later of the google-cloud-bigquery library use a Row class to parse rows from a table or query.

    For example to print out the results from a query with a schema

    [
       {
            u'type': u'STRING',
            u'name': u'word',
            u'mode': u'NULLABLE'
        },
        {
            u'type': u'INTEGER',
            u'name': u'word_count',
            u'mode': u'NULLABLE'
        },
        {
            u'type': u'INTEGER',
            u'name': u'corpus_date',
            u'mode': u'NULLABLE'
        },
    ]
    

    as in your example, one could do

    query = client.query('...')
    rows = query.result()
    for row in rows:
        # Access by column index.
        print('word: {}'.format(row[0]))
        # Access by column name.
        # The library parses the result into an integer object,
        # based on the schema.
        print('word_count: {}'.format(row['word_count']))
        # Access by column name, like an attribute.
        print('corpus_date: {}'.format(row.corpus_date))
    

    In version 0.29.0 (not yet released as of 2017-12-04), there will be methods for keys(), values(), items(), and get(), just like a built-in dictionary object. (Added in PR #4393) So, to convert rows to a JSON-like dictionary in 0.29.0:

    query = client.query('...')
    rows = query.result()
    for row in rows:
        row_json = dict(row.items())
    

提交回复
热议问题