How To Convert DB Data Into JSON Format

Posted By : Nikhil Verma | 19-Nov-2021

ERP

Loading...

Before Implementation, Let’s shed some light on JSON:

  • JSON format invented by Douglas Crockford in 2000
  • Support all the programming languages
  • Use of JSON data exchange the data between webserver and API
  • JSON is lighter and faster than xml format
  • APIs and web service uses the json format

Do you know what JSON (JavaScript Object Notation) Is?

Response: JSON is a quality portfolio format and data exchange portfolio with human understandable text to store and pass data objects. JSON format data in the key value pair. JSON values can be of (String, Number, Objects, Array, Boolean, Null). Often JSON is used for serializing the data (objective data to json) and transferring the data between connections.

Step:1:

import json

import psycopg2

// if object is UUID field

from uuid import UUID

Step:2

//Database Connection Details

def get_db(db_name='mydb'):

return psycopg2.connect(database=db_name,user='mydb',host='localhost',password='mydb')

Step: 3

//This function return the data from the database

def run_query(query, args=(), one=False):

cur = get_db().cursor()

cur.execute(query, args)

r = [dict((cur.description[i][0], value) \

for i, value in enumerate(row)) for row in cur.fetchall()]

cur.connection.close()

return (r[0] if r else None) if one else r

Step: 4

// function call with query and hold database data into query

query = run_query('select * from table_name')

Step: 5

//// if object is UUID field

class UUIDEncoder(json.JSONEncoder):

def default(self, object):

if isinstance(object, UUID):

return object.hex

return json.JSONEncoder.default(self, object)

Step: 6

// Here db data converting to json format

db_record_in_json_format = json.dumps(query, cls=UUIDEncoder)

print(db_record_in_json_format)

Output should be:

[

{

"name": "xyz",

"age": 36,

"add": "unknown address",

"contact": number

},

{

"name": "def",

"age": 23,

"add": "unknown address",

"contact": number

}

}

If you follow the above steps, you will get JSON data. This step makes it easy to make db data to JSON dumps.

We are an ERP development company that excels in providing complete enterprise solutions for diverse business needs and use-cases. Our seasoned developers use the latest tech stack and next-gen technologies to build scalable enterprise solutions with custom features. To learn more about our custom ERP application development services, contact us at [email protected].