Extract values from a JSON File
To create a JSON file open a text editor either notepad or VSCode then copy the above code and save the code with the .json extension.
{“criteria”: [
{“locationParam”: “[ALL:03232434]” },
{“variableParam”: “[00060, 00065]” }
]}
Fetch all Values from JSON file
Import JSON from the modules. Open the JSON file in read-only mode and load the JSON data into a variable using the Python load() function. Print the variable where the JSON data is loaded. The load function stores the JSON data as a Python dictionary of key-value pairs.
Python3
import json with open ( 'exam.json' , 'r' ) as json_File : sample_load_file = json.load(json_File) print (sample_load_file) |
Output:
Fetch specific Values from the JSON file
Import JSON from the modules. Open the JSON file in read-only mode using the Python with() function. Load the JSON data into a variable using the Python load() function. Now, get the value of keys in a variable. Now convert the value of the dictionary into a list and slice the string using the split function.
Python3
import json with open ( 'exam.json' , 'r' ) as json_File: sample_load_file = json.load(json_File) # getting hold of all values inside # the dictionary test = sample_load_file[ 'criteria' ] # getting hold of the values of # variableParam test1 = test[ 1 ].values() test2 = list (test1)[ 0 ] test3 = test2[ 1 : - 1 ].split( "," ) print (test3[ 1 ]) |
Output: