I am trying to access a value in a json file using python. In the imgur link, the value I am trying to access is the "NUM" nested in "args". My main logic is reading in the JSON file, then using pandas to normalize the json.I have tried using .loc to try and find 'args' but I need help with another way or option. [1]: https://i.stack.imgur.com/n6hOg.png
Here is my code snippet along with the terminal error I am getting
def readInJSON(json):
df = pandas.json_normalize(json)
goto_rows = [i for i in df.loc[df['mnemonic'] == 'PLD_CCD_EXPOSE_CLOSED'].index]
commandDates = list(df['utc_time'])
numIDs = list(df['args']) #tried using list typing
print(type(df['args'])) #couldnt get a typing from it either
args = df['args'] #tried just using it like a regular list
args = [i for i in df.loc[df['args']]] #tried using .loc from pandas as well
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/core/frame.py", line 3505, in getitem indexer = self.columns.get_loc(key) File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/pandas/core/indexes/base.py", line 3623, in get_loc raise KeyError(key) from err KeyError: 'args'
CodePudding user response:
This is how you can access value of NUM
:
import json
file = open('data.json')
data = json.load(file)
NUM = data[1]["args"]["NUM"]
# NUM = 20.0
file.close()
CodePudding user response:
The JSON structure appears to be a list of dictionaries. Those dictionaries may or may not have a 'args' key. The value associated with 'args' is expected to be a dictionary. That dictionary may contains a 'NUM' key. If 'NUM' exists, append its value to a list. Return the list.
def readInJSON(json):
numvals = []
for d in json:
if (args := d.get('args')):
if isinstance(args, dict) and (num := args.get('NUM')):
numvals.append(num)
return numvals
A better approach might be to write the function so that it handles the input JSON file like this:
import json
def readInJSON(filename):
with open(filename) as jdata:
numvals = []
for d in json.load(jdata):
if (args := d.get('args')):
if isinstance(args, dict) and (num := args.get('NUM')):
numvals.append(num)
return numvals