0

would like to transform a row-based JSON in a column-based JSON. I receive the JSON in a row-based form and will do some visualization with it, which would be easier in a column-based form.

row-based would look something like this:

{
  "0": {
    "fname": "John", 
    "lname": "Miller", 
    "age": 50
  }, 
  "1": {
    "fname": "Eve", 
    "lname": "Johnson", 
    "age": 40
  }...

Example column-based:

{
  "fname": {
    "0" : "John", 
    "1" : "Eve"
  }, 
  "lname": {
    "0" : "Miller", 
    "1" : "Johnson"
  }, 
  "age": {
    "0": 50, 
    "1" : 40
  }...

Is there a more efficient way than just looping through all elements and rewriting the JSON completely with python?

Thanks!

1
  • 2
    You'll have to read the JSON string into a Python object, and then extract the properties you want, to write them out in the order you want. There's no magic, here. Commented Dec 13, 2020 at 10:58

1 Answer 1

1

You should use pandas module, well fitting.

import pandas as pd
data = '''
{ "0": { "fname": "John", "lname": "Miller", "age": 50 }, "1": { "fname": "Eve", "lname": "Johnson", "age": 40 }}
'''
dataNew = pd.read_json(data,orient='index').to_json()
print(dataNew)

{"fname":{"0":"John","1":"Eve"},"lname":{"0":"Miller","1":"Johnson"},"age":{"0":50,"1":40}}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.