MeatMan
MeatMan

Reputation: 43

Reading an int from a json file

I'm new to Python and I am trying to get a ton of user info from my website and save the usergroups that each person has

I've been able to save the response to json but I cannot figure out how to read a in that is returned

My json File

{
    "pagination": {
        "current_page": 1,
        "last_page": 9,
        "per_page": 20,
        "shown": 20,
        "total": 173
    },

I don't want to show too much since there are emails, etc. saved in my file.

Specifically, I am looking to save the value for "total"

Attempt

with open(pathFile) as json_file:

    # read json file line by line
    for line in json_file.readlines():

        # create python dict from json object
        json_dict = json.loads(line)

        # check if "body" (lowercased) contains any of the keywords
        if any(keyword in json_dict["total"].lower() for keyword in keywords):
            print(json_dict["pagination"])

Error Message

Exception has occurred: JSONDecodeError
Expecting property name enclosed in double quotes: line 2 column 1 (char 2)
  File "C:\Users\New User\Desktop\path thing", line 43, in <module>
    json_dict = json.loads(line)

Upvotes: 2

Views: 503

Answers (1)

Andrew Allaire
Andrew Allaire

Reputation: 1330

Do not try to read each line, just use json.load on the entire file.

import json

with open(filePath, "r") as json_file:
    data = json.load(json_file)

total = data["pagination"]["total"]
print(total)

Upvotes: 2

Related Questions