Skip to content

Instantly share code, notes, and snippets.

@chrisbeardy
Created December 10, 2020 20:02
Show Gist options
  • Save chrisbeardy/9a326d760191c7812ee4c1fb2408affd to your computer and use it in GitHub Desktop.
Save chrisbeardy/9a326d760191c7812ee4c1fb2408affd to your computer and use it in GitHub Desktop.
json_problem
# I have a json file which looks something like this
#
# {
# "a.a" : "hello",
# "a.b" : "world",
# "a.c.a" : 4,
# "a.c.b" : 5.5,
# "a.c.c.a" : "hi",
# "a.c.c.b" : "again",
# "b.a.a" : 6,
# "b.a.b" : 7.0,
# "c.a[0]" : 6,
# "c.a[1]" : 7,
# "c.a[2]" : 8,
# "c.b.a" : 9,
# "c.c[0].a" : 10,
# "c.c[0].b" : 11,
# "c.c[1].a" : 12,
# "c.c[1].b" : 13,
# "d.a[0][0].a" : 1,
# "d.a[0][0].b" : 11,
# "d.a[0][1].a" : 2,
# "d.a[0][1].b" : 22,
# "d.a[1][0].a" : 3,
# "d.a[1][0].b" : 33,
# "d.a[1][1].a" : 4,
# "d.a[1][1].b" : 44,
# "e[0][0]" : 1,
# "e[0][1]" : 2,
# "e[1][0]" : 3,
# "e[1][1]" : 4
# }
# you catch the drift
# I can read this in easily and deserialise it to a dict:
the_dict = {
"a.a" : "hello",
"a.b" : "world",
"a.c.a" : 4,
"a.c.b" : 5.5,
"a.c.c.a" : "hi",
"a.c.c.b" : "again",
"b.a.a" : 6,
"b.a.b" : 7.0,
"c.a[0]" : 6,
"c.a[1]" : 7,
"c.a[2]" : 8,
"c.b.a" : 9,
"c.c[0].a" : 10,
"c.c[0].b" : 11,
"c.c[1].a" : 12,
"c.c[1].b" : 13,
"d.a[0][0].a" : 1,
"d.a[0][0].b" : 11,
"d.a[0][1].a" : 2,
"d.a[0][1].b" : 22,
"d.a[1][0].a" : 3,
"d.a[1][0].b" : 33,
"d.a[1][1].a" : 4,
"d.a[1][1].b" : 44,
"e[0][0]" : 1,
"e[0][1]" : 2,
"e[1][0]" : 3,
"e[1][1]" : 4
}
# what i want to be able to do is have a function which will take this
# dict and convert it to a new dictionary which can then be easily
# serialised into a json file
# which looks more like this:
# {
# "a": {
# "a" : "hello",
# "b" : "world",
# "c" : {
# "a" : 4,
# "b" : 5.5,
# "c" : {
# "a" : "hi",
# "b" : "again"
# }
# }
# },
# "b" : {
# "a" : {
# "a" : 6,
# "b" : 7.0
# }
# },
# "c" : {
# "a" : [6, 7, 8],
# "b" : {
# "a" : 9
# },
# "c" : [
# {
# "a" : 10,
# "b" : 11
# },
# {
# "a" : 12,
# "b" : 13
# }
# ]
# }
# "d" : {
# "a" : [
# [
# {
# "a" : 1,
# "b" : 11
# },
# {
# "a" : 2,
# "b" : 22
# }
# ],
# [
# {
# "a" : 3,
# "b" : 33
# },
# {
# "a" : 4,
# "b" : 44
# }
# ]
# ]
# },
# "e" : [[1,2], [3,4]]
# }
def old_dict_to_new_dict(old_dict):
# do magic
new_dict = the_dict.copy()
return new_dict
new_dict = old_dict_to_new_dict(the_dict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment