Json & Python

Json (JavaScript Object Notation) is a text based data exchange format widely used in porting data to different languages and platforms. All most all programming languages have libraries to manage Json.

More details on PHP Json

Here are some common methods used for managing Json strings.

Serializing JSON:

We can use a set of data in python and convert or encode them to Json string. Python objects in the form of of list, dictionary , string , integer etc can be converted by using dumps().

json.dumps() : to convert Python objects to Json string ( Serializing )
json.dump() : to convert Python object to Json to use along with file object.

Following Python objects can be converted to respective Json format.
PythonJson
DictionaryObject
list, TupleArray
String , UnicodeString
int, long, floatNumber
Truetrue
Falsefalse
Nonenull

Deserializing

Data or string in the Json format can be decoded to get the objects in Python.

json.loads() : to convert Json data to Pyton Object ( Deserializing )
json.load() : converting Json data from file to Python object by using file object.
Here is a list of Json data which can be converted to Python objects.
JsonPython
ObjectDictionary
ArrayList
stringUnicode
Number (int ) int , long
Number ( real ) float
trueTrue
falseFalse
nullNone

MySQL Database records and Json format.

As the main requirement of Json is data exchange, here is the code to collect data from mysql table and then encode the same to get the data in Json format.

You can read more on MySQL connection and sqlalchemy here
from sqlalchemy import create_engine
engine = create_engine("mysql+mysqldb://userid:password@localhost/my_database")
my_connect = engine.connect()
import json
rs=my_connect.execute("SELECT * FROM  student Where class='Three'")
my_data= rs.fetchall() # a list 

j=json.dumps([dict(r) for r in my_data])

print(j)
my_connect.close()
Output
[{"id": 2, "name": "Max Ruin", "class": "Three", "mark": 85, "sex": "male"},
 {"id": 3, "name": "Arnold", "class": "Three", "mark": 55, "sex": "male"}, 
 {"id": 27, "name": "Big Nose", "class": "Three", "mark": 81, "sex": "female"}]


plus2net.com



Post your comments , suggestion , error , requirements etc here




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer