Janis Gustavian
Janis Gustavian

Reputation: 47

How to parse JSON file into Python list

I am trying to parse a JSON file into Python but failing to print any specific data I am trying to pull from JSON.

How can I put these JSON data in separate arrays, so I can play with them in Python?

This is the JSON file:

{
"Ask":
   {"0":[[9.13,30200],[9.14,106946],[9.15,53072],[9.16,58104],[9.17,45589]],
    "1":[[9.14,106946],[9.15,53072],[9.16,58104],[9.17,45589],[9.18,37521]] },

"Bid":
   {"0":[[9.12,198807],[9.11,1110],[9.1,42110],[9.09,84381],[9.08,98178]],
    "1":[[9.13,13500],[9.12,198807],[9.11,1110],[9.1,42110],[9.09,84381]]}
}

and this is my code:

import json

with open("JSON Directory") as BOB:
    data=json.load(BOB)

for x in data["Bid"]:
    print(x["0"])

I get this error:

TypeError: string indices must be integers

Upvotes: 4

Views: 17974

Answers (4)

dreftymac
dreftymac

Reputation: 32360

Quick Answer (TL;DR)

  • Convert Before

    for x in data["Bid"]:
      print(x["0"])
    
  • Into After

    for x in data["Bid"]:
      print(data["Bid"][x])
    

Problem

  • Python data reference to loaded JSON data is not producing the desired result

Solution

  • Correctly identify the JSON address as either a dictionary key or a string
  • In the original example print(x["0"]) is an incorrect reference because x is a string (dictionary key)
  • This can be verified by using using python pprint.pprint() to troubleshoot what you are looking for

Example

## import pprint 
## we use this to inspect the data to make sure we are
## working with what we expect

import pprint
pass

# [...] (loading code omitted)

for x in data["Bid"]:
  pprint.pprint(x)
# u'1'
# u'0'

Example Modified

## pprint the values

for x in data.values():
  pprint.pprint(x)

# {u'0': [[9.13, 30200],
#         [9.14, 106946],
#         [9.15, 53072],
#         [9.16, 58104],
#         [9.17, 45589]],
#  u'1': [[9.14, 106946],
#         [9.15, 53072],
#         [9.16, 58104],
#         [9.17, 45589],
#         [9.18, 37521]]}
# {u'0': [[9.12, 198807],
#         [9.11, 1110],
#         [9.1, 42110],
#         [9.09, 84381],
#         [9.08, 98178]],
#  u'1': [[9.13, 13500],
#         [9.12, 198807],
#         [9.11, 1110],
#         [9.1, 42110],
#         [9.09, 84381]]}

Example Corrected

## we are looking at dictionary keys with `x`
## if we want to iterate the dictionary keys in data["Bid"]
## we need to correctly reference what we are looking for

for x in data["Bid"]:
  print(data["Bid"][x])

# [[9.13, 13500], [9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381]]
# [[9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381], [9.08, 98178]]

Upvotes: 0

blhsing
blhsing

Reputation: 106455

The value data["Bid"] is a dict, and by iterating over a dict with:

for x in data["Bid"]:

you are actually iterating over the keys of the dict, which are strings and cannot be indexed with a non-integer like x["0"].

If you intend to iterate over the sub-lists under the 0 key of the data["Bid"] dict, you should instead do:

for x in data["Bid"]['0']:
    print(x)

Upvotes: 0

Wesley Ferreira
Wesley Ferreira

Reputation: 11

your for is loop in the keys of dict.

for x in data["Bid"]:
  print(type(x))
# <class 'str'>

try it:

for x in data['Bid']['0']:
 print(x)

or

for x in data['Bid'].values():
 print(x)

sorry for my English :)

Upvotes: 0

m.a.d.cat
m.a.d.cat

Reputation: 207

There's just a slight problem with your for loop.

james@VIII:~/Desktop$ ls
f.txt
james@VIII:~/Desktop$ cat f.txt 
{
"Ask":
   {"0":[[9.13,30200],[9.14,106946],[9.15,53072],[9.16,58104],[9.17,45589]],
    "1":[[9.14,106946],[9.15,53072],[9.16,58104],[9.17,45589],[9.18,37521]] },

"Bid":
   {"0":[[9.12,198807],[9.11,1110],[9.1,42110],[9.09,84381],[9.08,98178]],
    "1":[[9.13,13500],[9.12,198807],[9.11,1110],[9.1,42110],[9.09,84381]]}
}
james@VIII:~/Desktop$ python3
Python 3.6.7 (default, Oct 22 2018, 11:32:17) 
[GCC 8.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> with open('f.txt') as f_in:
...     data = json.load(f_in)
... 
>>> data
{'Ask': {'0': [[9.13, 30200], [9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589]], '1': [[9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589], [9.18, 37521]]}, 'Bid': {'0': [[9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381], [9.08, 98178]], '1': [[9.13, 13500], [9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381]]}}
>>> data['Ask']
{'0': [[9.13, 30200], [9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589]], '1': [[9.14, 106946], [9.15, 53072], [9.16, 58104], [9.17, 45589], [9.18, 37521]]}
>>> 
>>> data['Bid']
{'0': [[9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381], [9.08, 98178]], '1': [[9.13, 13500], [9.12, 198807], [9.11, 1110], [9.1, 42110], [9.09, 84381]]}
>>> for x in data['Bid']['0']:
...     print(x)
... 
[9.12, 198807]
[9.11, 1110]
[9.1, 42110]
[9.09, 84381]
[9.08, 98178]

Your for loop just needed to be changed a little.

PS you don't need to specify 'r' when reading the file.

You can also get individual values like this:

>>> for x in data['Bid']['0']:
...     print(str(x[0]) + ': ' + str(x[1]))
... 
9.12: 198807
9.11: 1110
9.1: 42110
9.09: 84381
9.08: 98178

Upvotes: 3

Related Questions