Abdullah
Abdullah

Reputation: 305

extracting data from JSON object with python

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

Upvotes: 0

Views: 45

Answers (1)

Dmitry Shevchenko
Dmitry Shevchenko

Reputation: 478

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]

Upvotes: 1

Related Questions