Python JSON

JSON (JavaScript object notation) is a syntax for storing and exchanging data.

Convert from JSON to Python

import json

# some JSON:
x =  '{ "name":"John", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:
print(y["age"])

Convert from Python to JSON

import json

# a Python object (dict):
x = {
  "name": "John",
  "age": 30,
  "city": "New York"
}

# convert into JSON:
y = json.dumps(x)

# the result is a JSON string:
print(y)

Convert from Python class to JSON

import json

class activities:
	def __init__(self, activity):
		self.activities = []
		self.activities.append(activity)
	def toJson(self):
		return json.dumps(self, default=lambda o: o.__dict__)		

class activity:
	def __init__(self, ref, name, start_datetime, end_datetime, location_name, track_ref, description, separatedByComma):  
		self.ref = ref
		self.name = name
		self.start_datetime = start_datetime
		self.end_datetime = end_datetime  
		self.location_name = location_name
		self.track_ref = track_ref  
		self.description = description
		self.presenters = []
		#split string by ,
		chunks = separatedByComma.split(',')
		for it in chunks:
			#print(it)
			self.presenters.append(	presenter(it, "Speaker") )
			
	def toJson(self):
		return json.dumps(self, default=lambda o: o.__dict__)
			

class presenter:
	def __init__(self, person_ref, role):  
		self.person_ref = person_ref  
		self.role = role
)

# create a object
oSession = activity("001"
, "Lession 1"
, "2021-02-01 08:00:00"
, "2021-02-01 09:00:00"
, "Virtual Event"
, "Track 1"
, "Bootstrap 4 Tutorial"
, "Speaker 1, Speaker 2"
)

# convert into JSON:
json_data = oSessions.toJson()

print (json_data)