1

I have a json file in following format:

{
"alpha":"12233321",
"beta":
      { 
       "beta1":12.2232,
       "beta2":23.4445
       },
"gamma":
      {
        "gamma1":23.12312,
        "gamma2":12.33445
       }
}

I want to store alpha in a variable, beta and gamma in a numpy arrays.

2
  • What have you tried so far? Commented Apr 19, 2020 at 5:34
  • I am actually clueless on how to start. Because i am confused as this json object contains a single variable and then sets of variables Commented Apr 19, 2020 at 5:38

2 Answers 2

2

Use:

import json
import numpy as np

with open("data.json", "r") as f: # data.json is your json file
    info = json.load(f)
    alpha = info["alpha"]
    beta = np.array(list(info["beta"].values())) # instantiate np array
    gamma = np.array(list(info["gamma"].values())) # instantiate np array

    print("Alpha:", alpha)
    print("Beta:", beta)
    print("Gamma:", gamma)

This prints:

Alpha: 12233321
Beta: [12.2232 23.4445]
Gamma: [23.12312 12.33445]
Sign up to request clarification or add additional context in comments.

Comments

0

Use pandas to read the json

import pandas as pd
import numpy as np

df = pd.read_json('<json_file>')

beta_array = np.array(df[~df.beta.isnull()].beta)
gamma_array = np.array(df[~df.gamma.isnull()].gamma)

3 Comments

There is actually a module that could be used instead of pandas, json. Using json.loads(string) the output would be a dict.
@jcaliz ValueError: Unexpected character found when decoding 'true'
@TomRobinson could you provide me an example on how will you work on this? also it is difficult to convert dicts to numpy ndarrays

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.