Home > Mobile >  I need help creating a simple python script that stores an attribute value from a custom json file
I need help creating a simple python script that stores an attribute value from a custom json file

Time:10-15

JSON file looks like this:

{"Clear":"Pass","Email":"[email protected]","ID":1234}

There are hundreds of json files with different email values, which is why I need a script to run against all files.

I need to extract out the value associated with the Email attribute, which is [email protected].

I tried using import json but I'm getting a decoder error:

    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Script looks like this:

import json
json_data = json.loads("file.json")
print (json_data["Email"]

Thanks!

CodePudding user response:

your script needs to open the file to get a file handle, than we can read the json. this sample contains code that can read the json file. to simulate this, it uses a string that is identical with the data coming from the file.

import json

#this is to read from the real json file
#file_name = 'email.json'
#with open(file_name, 'r') as f_obj:
   #json_data = json.load(f_obj)

# this is a string that equals the result from reading json file
json_data = '{"Clear":"Pass","Email":"[email protected]","ID":1234}'
json_data = json.loads(json_data)
print (json_data["Email"])

result: [email protected]

CodePudding user response:

import json
with open("file.json", 'r') as f:
    file_content = f.read()
    #convert json to python dict
    tmp = json.loads(file_content)
    email = tmp["Email"]

As already pointed out in previous comments, json.loads() take contents of a file rather than a file.

CodePudding user response:

According to the docs, json.loads() takes a str, bytes or bytearray as argument. So if you wan't to load a json file this way, you should pass the content of the file instead of its path.

import json
file = open("file.json", "r") # Opens file.json in read mode
file_data = file.read()
json_data = json.loads(file_data)
file.close() # Remember to close the file after using it

You can also use json.load() which takes a FILE as argument

import json
file = open("file.json", "r")
json_data = json.load(file)
file.close()
  • Related