object to json python code example
Example 1: print json python
import json
uglyjson = '{"firstnam":"James","surname":"Bond","mobile":["007-700-007","001-007-007-0007"]}'
parsed = json.loads(uglyjson)
print(json.dumps(parsed, indent=2, sort_keys=True))
Example 2: python json string to object
import json
x = '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x)
print(y["age"])
Example 3: Convert from JSON to Python
import json
x = '{ "name":"John", "age":30, "city":"New York"}'
y = json.loads(x)
print(y["age"])
Example 4: python object to json
jsonStr = json.dumps(myobject.__dict__)
Example 5: python to json
x = {
"name": "John",
"age": 30,
"city": "New York"
}
y = json.dumps(x)
Example 6: convert class object to json python
import json
class Laptop:
name = 'My Laptop'
processor = 'Intel Core'
laptop1 = Laptop()
laptop1.name = 'Dell Alienware'
laptop1.processor = 'Intel Core i7'
jsonStr = json.dumps(laptop1.__dict__)
print(jsonStr)