10 examples of 'create json object in python' in Python

Every line of 'create json object in python' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your Python code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
25def python_to_json(python_data):
26 '''Convert python data (tuple, list, dict, etc) into json string'''
27 json_str = json.dumps(python_data, indent=4)
28 return json_str
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

68def to_json(jsobj):
69 """Convert a JSON object to a human-readable string."""
70 return call_json(json.dumps, jsobj)
23def object_2_json(obj):
24 '''
25 py字典、数据转成json字符转
26 '''
27 if obj is None:
28 obj = {}
29 return json.dumps(obj, cls=CJsonEncoder)
5def _custom_json_handler(obj):
6 if isinstance(obj, (datetime.datetime, datetime.time)):
7 return obj.isoformat()
50def json2obj(data): return json.loads(data, object_hook=_json_object_hook)
202def convert_to_json(object):
203 return object.__str__()
5def render_to_json(python_dict, response_class=HttpResponse, status=200):
6 return response_class(dumps(python_dict),
7 mimetype='application/json',
8 status=status)
22def json_object(obj, fields):
23 def get_recur_attr(obj, attrs):
24 attr = attrs.pop(0)
25 val = getattr(obj, attr, None)
26 if callable(val):
27 val = val()
28 if len(attrs) > 0:
29 return get_recur_attr(val, attrs)
30 else:
31 return val
32
33 object_str = []
34 for field in fields:
35 value = get_recur_attr(obj, field.split('.'))
36
37 if value is None:
38 object_str.append('"%s": null' % field)
39
40 elif type(value) == bool:
41 object_str.append('"%s": %s' % (field, str(value).lower()))
42
43 elif type(value) == unicode or type(value) == str:
44 object_str.append('"%s": "%s"' % (field, json_string(value)))
45
46 elif type(value) == int:
47 object_str.append('"%s": "%d"' % (field, value))
48
49 elif isinstance(value, datetime):
50 object_str.append('"%s": "%s"' %
51 (field, value.strftime("%d/%m/%y %H:%M")))
52
53 elif value.__class__.__name__ == 'ManyRelatedManager':
54 ids = [ str(x.id) for x in value.all() ]
55 object_str.append('"%s": [%s]' % (field, ",".join(ids)))
56
57 return "{" + ",".join(object_str) + "}"
14def from_json(json_object):
15 if '__class__' in json_object:
16 if json_object['__class__'] == 'time.asctime':
17 return time.strptime(json_object['__value__'])
18 if json_object['__class__'] == 'bytes':
19 return bytes(json_object['__value__'])
20 return json_object
218def from_json(json_object):
219 """For py3 compat"""
220 if '__class__' in json_object:
221 if json_object['__class__'] == 'bytes':
222 return codecs.decode(json_object['__value__'].encode(), 'base64')
223 return json_object

Related snippets