'How do I print and filter a Json file in Python [closed]

code:

import json
with open('routes.txt') as routes:
    allRoutes = json.load(routes)

print(allRoutes)

Am I doing anything wrong because I get an error and yes routes.txt is a file. I would also like to filter it out so I can get a specific value but I can work it out.

my error:

Traceback (most recent call last):
  File "/Users/-/PycharmProjects/Bots/VA/Cargolux/cargolux_bot/code/rotw.py", line 5, in <module>
    allRoutes = json.load(routes)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 293, in load
    return loads(fp.read(),
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/__init__.py", line 357, in loads
    return _default_decoder.decode(s)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/json/decoder.py", line 353, in raw_decode
    obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

Process finished with exit code 1


Solution 1:[1]

From your error it looks like the file has some structural problems. A JSON should have a shape like the example below. Also have a look at Working with JSON for further examples.

{
  "key1": "value 1",
  "key2": "value 2",
  "key3": [
    {
      "key4": "value 3",
      "key5": 3,
      "key6": [
        "value 4"
      ]
    },
    {
      "key4": "value 4",
      "key5": 6,
      "key6": [
        "value 5",
        "value 6"
      ]
    }
  ]
}

About filtering have a look at this How to filter json array in python. Does it answer your question?

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1