1

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"
 }
]

3 Answers 3

4
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'}]
Sign up to request clarification or add additional context in comments.

Comments

3

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))

1 Comment

I am using Flask-MySQL
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.