Skip to content
This repository has been archived by the owner on Dec 19, 2022. It is now read-only.

added a python-based json inverting function #381

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions Python/json_inversion/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# JSON Inversion
by Nate Allen (github.com/nateonmission)

I frequently have data that is shaped like this:

```
{
"age":
{
"user_1": 25,
"user_2": 35,
"user_3": 40
},
"first_name":
{
"user_1": "John",
"user_2": "Mary",
"user_3": "Lee"
}
}
```

BUT I need it to look like this:
```
{
"user_1":
{
"age": 25,
first_name: "John"
},
"user_2":
{
"age": 35,
"first_name": "Mary"
},
"user_3":
{
"age": 40,
"first_name": "Lee"
}
}

```

This algorithm does just that.
24 changes: 24 additions & 0 deletions Python/json_inversion/json_inversion.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@


def invert_json(json_data, output_file_name="output.txt")
new_attributes = []
new_dict_of_dicts = {}
data = json.loads(json_data)

for key in data.keys():
new_attributes.append(key)

for key in data[new_attributes[0]].keys():
new_dict_of_dicts[key] = {}

for category, obj in data.items():
for person, value in obj.items():
new_dict_of_dicts[person][category] = value

back_to_json_str = json.dumps(new_dict_of_dicts)

# Print to outputfile
with open(output_file_name, "w") as outfile:
outfile.write(back_to_json_str)

return back_to_json_str