4

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
6
  • I did that sorry, I didnt post it, there is no problem with reading the file Commented Apr 19, 2019 at 21:42
  • @YashPokar 'r' is the default mode for opening files. Commented Apr 19, 2019 at 21:43
  • I have made Python read the JSON succesfully, there is no problem with reading the file. Problem is I cant get the values for Bid "0" Commented Apr 19, 2019 at 21:44
  • 2
    data['Bid'] gives you a dictionary. Your need to look up how to iterate through a dictionary. Commented Apr 19, 2019 at 21:45
  • 1
    adding "print x" to the line before your error should clear up your understanding. When you iterate over a dictionary, you get the key, not the value. Commented Apr 19, 2019 at 21:49

4 Answers 4

3

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
Sign up to request clarification or add additional context in comments.

2 Comments

How can I get just 9.12 for example ? I am trying to write a generalized code to get for example i:1to10 ['Bid']['0'][i]-['Ask']['0'][i]
It looks ugly but here you go hahaha: data['Bid']['0'][0][0] (prints 9.12)
0

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 :)

Comments

0

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)

7 Comments

strings and cannot be indexed with an integer like x["0"] in python, strings actually can be indexed with an integer. For example, x[0] would return a result instead of an error (not the expected result though, but that is a separate issue).
Oops that was a typo indeed. Fixed then.
Great ! Thank you. Can you show me an for example to store these Bid 0 values in an array
@JanisGustavian You don't need a for loop to store the data["Bid"]['0'] list because it is already a list. Just assign it to a variable directly: lst = data["Bid"]['0']
I got you, thank you for your insightful comment. I am trying to make some calculations such as i : 1 to 10 data["Bid"]['i'] First Index -data["Ask"]['i'] First Index
|
0

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]]

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.