root
root

Reputation: 177

JSON file modification with Python

I'm trying to write a Python script to read data from a JSON file, do some calculations with it and then write output to a new JSON file. But I can't seem to automate the JSON reading process. I get this error. Could you please help me with this issue? Thank you very much

print([a[0]][b[1]][c[1]])
TypeError: list indices must be integers or slices, not str

test.json

{
      "male": {
            "jack": {
                  "id": "001",
                  "telephone": "+31 2225 345",
                  "address": "10 Street, Aukland",
                  "balance": "1500"
            },
            "john": {
                  "id": "002",
                  "telephone": "+31 6542 365",
                  "address": "Main street, Hanota",
                  "balance": "2500"
            }
      },

      "female": {
            "kay": {
                  "id": "00",
                  "telephone": "+31 6542 365",
                  "address": "Main street, Kiro",
                  "balance": "500"
            }
      }
}

test.py

with open("q.json") as datafile:
    data = json.load(datafile)

    a = ['male', 'female']
    b = ['jack', 'john', 'kay']
    c = ['id', 'telephone', 'address', 'balance']

    print([a[1]][b[1]][c[1]])

Upvotes: 0

Views: 89

Answers (2)

velis
velis

Reputation: 10075

If I understand you correctly, you really want to print data from the JSON, not your intermediary arrays.

So:

print(data['Male'])  # will print the entire Male subsection
print(data['Male']['Jack'])  # will print the entire Jack record
print(data['Male']['Jack']['telephone'])  # will print Jack's telephone

But to relate that with your intermediary arrays too:

print(data[a[0]])  # will print the entire Male subsection
print(data[a[0]][b[0]])  # will print the entire Jack record
print(data[a[0]][b[0]][c[0]])  # will print Jack's telephone

assuming that you declare a correctly:

a = ['Male', 'Female']  # Notice the capitals

Upvotes: 1

Tobias S
Tobias S

Reputation: 1275

I dont know, how you access data in your code, because you directly write hard coded values into a, b and c. In addition, you could print out your test via: print(a[1], b[1], c[1]).

Upvotes: 0

Related Questions