-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathordered_json.py
74 lines (61 loc) · 1.31 KB
/
ordered_json.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "ipetrash"
# SOURCE: https://stackoverflow.com/a/6921760/5909792
# SOURCE: https://stackoverflow.com/a/23820416/5909792
import json
from collections import OrderedDict
json_data = {"foo": 1, "bar": 2, "abc": {"a": 1, "b": 2, "c": 3}}
ordered_json_data = OrderedDict()
ordered_json_data["foo"] = 1
ordered_json_data["bar"] = 2
ordered_json_data["abc"] = OrderedDict()
ordered_json_data["abc"]["a"] = 1
ordered_json_data["abc"]["b"] = 2
ordered_json_data["abc"]["c"] = 3
print("Dumps:")
print(json.dumps(json_data, indent=4))
# {
# "bar": 2,
# "abc": {
# "a": 1,
# "b": 2,
# "c": 3
# },
# "foo": 1
# }
ordered_json_str = json.dumps(ordered_json_data, indent=4)
print(ordered_json_str)
# {
# "foo": 1,
# "bar": 2,
# "abc": {
# "a": 1,
# "b": 2,
# "c": 3
# }
# }
print()
print("Loads:")
data = json.loads(ordered_json_str)
print(json.dumps(data, indent=4))
# {
# "bar": 2,
# "abc": {
# "c": 3,
# "b": 2,
# "a": 1
# },
# "foo": 1
# }
data = json.loads(ordered_json_str, object_pairs_hook=OrderedDict)
print(json.dumps(data, indent=4))
# {
# "foo": 1,
# "bar": 2,
# "abc": {
# "a": 1,
# "b": 2,
# "c": 3
# }
# }