0

JSON file looks like this:

{"Clear":"Pass","Email":"noname@email.com","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 nooname@email.com.

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!

  • `Be sure to remember to invoke json.loads() on the contents of the file, as opposed to the file path of that JSON` https://stackoverflow.com/a/58647394/11280068 – Nicholas Hansen-Feruch Oct 14 '22 at 17:43

3 Answers3

1

According to the docs, json.loads() takes a str, bytes or bytearray as argument. So if you want 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()
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jvx8ss
  • 529
  • 2
  • 12
0

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":"noname@email.com","ID":1234}'
json_data = json.loads(json_data)
print (json_data["Email"])

result: noname@email.com

lroth
  • 367
  • 1
  • 2
  • 4
0
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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
PRINCE
  • 56
  • 3