cpwah
cpwah

Reputation: 141

Python - read json file

I am trying to read the JSON file in python and it is successfully however some top values are skipped. I am trying to debug the reason. Here is the the code.

data = json.load(open('pre.txt'))

for key,val in data['outputs'].items():
    print key
    print data['outputs'][key]['feat_left']

EDIT Here is the snapshot the file. I want to read key and feat_left for outputs

{
  "outputs": {
    "/home/113267806.jpg": {
      "feat_left": [
        2.369331121444702, 
        -1.1544183492660522
      ], 
      "feat_right": [
        2.2432730197906494, 
        -0.896904468536377
      ]
    }, 
    "/home/115061965.jpg": {
      "feat_left": [
        1.8996189832687378, 
        -1.3713303804397583
      ], 
      "feat_right": [
        1.908974051475525, 
        -1.4422794580459595
      ]
    }, 
    "/home/119306609.jpg": {
      "feat_left": [
        -0.7765399217605591, 
        -1.690917730331421
      ], 
      "feat_right": [
        -1.1964678764343262, 
        -1.9359161853790283
      ]
    }
  }
 }

P.S: Thanks to Rahul K P for the code

Upvotes: 0

Views: 907

Answers (4)

Andrea D'Urso
Andrea D'Urso

Reputation: 1

Try this:

for key, val in data['outputs'].items():
    print key, val['feat_left'] 
#output /home/119306609.jpg [-0.7765399217605591, -1.690917730331421]

This get every key and element within 'feat_left' Then you can display in the page however you like

Upvotes: 0

aidanmelen
aidanmelen

Reputation: 6614

i think you want:

for key, val in data['outputs'].items():
    if 'feat_left' in val:
        print key, data['outputs'][key]['feat_left']

Upvotes: 2

Supahupe
Supahupe

Reputation: 515

If you just want to print the content of the file by using a for-loop, you can try like this:

data = json.load(open('pre.txt')
for key,val in data['outputs'].items():
      print key
      print val[0] #this will print the array and its values below "feat_left", if the json is consistent

A more robust solution could look like this:

data = json.load(open('pre.txt')
for key,val in data['outputs'].items():
      print key
      for feat_key, feat_val in val.items():
            if feat_key == 'feat_left':
                 print feat_val

Code is untested, give it a try.

Upvotes: 0

Hossein
Hossein

Reputation: 2111

No top values are skipped. There are 45875 items in your data['output'] object. Try the following code:

len(data['outputs'].items())

And there are exactly 45875 items in your JSON file. Just note that JSON object is an unordered collection in python, like dict.

Upvotes: 2

Related Questions