简体   繁体   中英

Converting result to json in python flask

I am creating apis in python flask. I am using MySQL for database and got data successfully using SELECT query. I have returned the data in json format using jsonify of flask. What i want to ask is, I am getting json in following format after jsonify that uses integer as index

[
 [
  1, 
  "FURNITURE", 
  "INDOOR FURNITURE"
 ], 
 [
  2, 
  "AUTOMOBILES", 
  "CARS, BIKES"
 ], 
 [
  3, 
  "LAPTOP & ACCESSORIES", 
  "LAPTOP, MOUSE, KEY BOARD, PENDRIVE"
 ]
]

It is fine and i can work with this but I am looking for json that has database table attribute as its index like we can get in nodejs so it will be easier to work in font end. I want to have json in following format where index are my database table column name.

[
 { "CATEGORY_ID":1,
   "CATEGORY_NAME":"FURNITURE",
   "DESCRIPTION":"INDOOR FURNITURE"
 },
 { "CATEGORY_ID":2,
   "CATEGORY_NAME":"AUTOMOBILES",
   "DESCRIPTION":"CARS, BIKES"
 },
 { "CATEGORY_ID":3,
   "CATEGORY_NAME":"LAPTOP & ACCESSORIES",
   "DESCRIPTION":"LAPTOP, MOUSE, KEY BOARD, PENDRIVE"
 }
]

The question doesn't specify your SQL adapter, but if you're using SQLAlchemy with Flask, here's an example of how to query a database and output the result in your desired format:

from flask import Flask
from models import db
import json

app = Flask(__name__)

app.config['SQLALCHEMY_DATABASE_URI'] = 'your_database_connection_string'
db.init_app(app)

result = db.session.execute("SELECT * FROM categories WHERE id = :id", {"id":999})

# If no rows were returned (e.g., an UPDATE or DELETE), return an empty list
if result.returns_rows == False:
    response = []

# Convert the response to a plain list of dicts
else:
    response = [dict(row.items()) for row in result]

# Output the query result as JSON
print(json.dumps(response))

i find solution with sql-alchemy better approach. still if want the solution as per problem statement then , here is a solution

import json 

def conv_func(list_data):
    dic ={ "CATEGORY_ID":list_data[0],
          "CATEGORY_NAME":list_data[1],
          "DESCRIPTION":list_data[2]
          }
    return dic


data = '''[[
  1, 
  "FURNITURE", 
  "INDOOR FURNITURE"
 ], 
 [
  2, 
  "AUTOMOBILES", 
  "CARS, BIKES"
 ], 
 [
  3, 
  "LAPTOP & ACCESSORIES", 
  "LAPTOP, MOUSE, KEY BOARD, PENDRIVE"
 ]
]'''

data = json.loads(data)



new_data=[]
for i in data:
        new_data.append(conv_func(i))

print(new_data)
import pymysql
cur = mysql.connect().cursor(pymysql.cursors.DictCursor)
cur.execute(sql)
row = cur.fetchall()
print row

[{u'symbol': u'AAPL'}, {u'symbol': u'SQ'}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM