-1

I have created JSON file like this and I want to access email this is the JSON file

{
            "customers": {
                "OscarLang": {
                    "email": "gmail@gmail.com",
                    "events": []
                },
                "foretz-abdo": {
                    "email": "hotmail@hotmail.com",
                    "events": []
                },
                "testuser": {
                    "email": "test@hotmail.com",
                    "events": []
                },
                "AAS": {
                    "email": "osdaadawdaw@asdad.com",
                    "events": []
                }
            }
        }

and this what I tried

 sources = ["customers.json"]
    for source in sources:
        data = util.get_data_item(source)
        if data is None or len(data) == 0:
            continue
        register = json.loads(data)
        for json_obj in register['customers']:
            print(json_obj)
            try:
                emailaddress = json_obj['email']
            except Exception as e:
                emailaddress = None

            print(emailaddress)

when I print emailaddress I get NONE

Puneet Singh
  • 3,477
  • 1
  • 26
  • 39
Abd
  • 21
  • 2
  • 2
    Hi Abdo, please read up on [asking questions](https://stackoverflow.com/help/how-to-ask) before writing your next question! Happy coding :) – Diggy. May 14 '20 at 13:24
  • Does this answer your question? [How to parse JSON in Python?](https://stackoverflow.com/questions/7771011/how-to-parse-json-in-python) – medic17 May 14 '20 at 19:32

1 Answers1

1

Welcome to stack overflow.

See if something like this will work for you:

Project Tree:

project
  |__customers.json
  |
  |__customers.py

customers.json file

{
  "customers": {
    "OscarLang": {
      "email": "gmail@gmail.com",
      "events": []
    },
    "foretz-abdo": {
      "email": "hotmail@hotmail.com",
      "events": []
    },
    "testuser": {
      "email": "test@hotmail.com",
      "events": []
    },
    "AAS": {
      "email": "osdaadawdaw@asdad.com",
      "events": []
    }
  }
}

customers.py file

# Import Python's json package
import json

# Specify the json file to work with
sources = 'customers.json'

# Open the json file
with open(sources) as json_file:
    # Extract the data from the json file
    data = json.load(json_file)

    # Iterate over each customer in the file
    for customer in data['customers']:
        # Print each customer's e-mail address
        try:
            email = data['customers'][customer]['email']
            print(email)
        except KeyError as err:
            print(f"Email not found for {customer}")
Lateralus
  • 792
  • 9
  • 19
  • I tried this but I got this error TypeError: list indices must be integers – Abd May 14 '20 at 20:29
  • Do you have the full stack trace for the error? I updated my answer to show the json file and format I used to run – Lateralus May 14 '20 at 20:32