python
import simplejson as json
data = {'name': 'John', 'age': 30, 'city': 'New York'}
json_data = json.dumps(data)
print(json_data)
json_data = '{"name": "John", "age": 30, "city": "New York"}'
data = json.loads(json_data)
print(data)
{"name": "John", "age": 30, "city": "New York"}
{'name': 'John', 'age': 30, 'city': 'New York'}
python
import simplejson as json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def toJSON(self):
return {'name': self.name, 'age': self.age}
def encode_person(obj):
if isinstance(obj, Person):
return obj.toJSON()
raise TypeError('Object of type Person is not JSON serializable')
def decode_person(dct):
if 'name' in dct and 'age' in dct:
return Person(dct['name'], dct['age'])
return dct
data = {'person': Person('John', 30)}
json_data = json.dumps(data, default=encode_person)
print(json_data)
json_data = '{"person": {"name": "John", "age": 30}}'
data = json.loads(json_data, object_hook=decode_person)
print(data['person'].name)
print(data['person'].age)
{"person": {"name": "John", "age": 30}}
John
30
python
import simplejson as json
data = {'name': 'John', 'age': 30, 'city': 'New York'}
json_data = json.dumps(data, ensure_ascii=True)
print(json_data)
json_data = json.dumps(data, sort_keys=True)
print(json_data)
json_data = json.dumps(data, indent=4)
print(json_data)
{"name": "John", "age": 30, "city": "New York"}
{"age": 30, "city": "New York", "name": "John"}
{
"name": "John",
"age": 30,
"city": "New York"
}