0

I am trying to get data into SAMPLES and LABELS variables from JSON objects which looks like this.

{
"samples": [
    [
        28,
        25,
        95
    ],
    [
        21,
        13,
        70
    ],
    [
        13,
        21,
        70
    ]
],
"labels": [
    1,
    2,
    3
  ]
 }

the code I am using

with open(data, 'r') as d:
complete_data = json.load(d)
for a in complete_data:
    samples = a['samples']
    lables = a['lables']

but its says

samples = a['samples']

TypeError: string indices must be integers

5
  • remove the for-loop - use samples = complete_data['samples'], etc Commented Feb 18, 2020 at 14:47
  • You trying to use string representation of a dictionary. You should convert it yo dictionary first. Use ast.literal_eval to convert dictionary Commented Feb 18, 2020 at 14:48
  • @ikibir, I searched about ast.literal_eval, it says it is used to evaluate the input, to check if it is valid or not. can you please guide me more about it? Commented Feb 18, 2020 at 15:02
  • @Abdullah on which line does that error occur? Commented Feb 18, 2020 at 15:04
  • @EdWard, your solution worked, I took the variables out of with block and it worked. Thank you so much Commented Feb 18, 2020 at 15:07

1 Answer 1

1

To get data from 'samples' and 'labels' You don't need to use loop. Try this:

import json

with open('data.json', 'r') as d:
    complete_data = json.load(d)

samples = complete_data['samples']
labels = complete_data['labels']

print(samples)
print(labels)

Output:

[[28, 25, 95], [21, 13, 70], [13, 21, 70]]
[1, 2, 3]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.