0

Duplicate of my question: How to read json folder data using Python?

Thanks to all answered the question

JanF
  • 117
  • 2
  • 10
  • 1
    Related: [How do I create a variable number of variables?](https://stackoverflow.com/q/1373164/4518341) The best output IMO would be something like `device_statuses = {"device1": 0, "device2": 1, "device3": 1}`. Then if you need a list of devices, use `device_statuses.keys()`, which you can cast to `list` if needed. – wjandrea Jan 28 '20 at 01:16
  • Is that a typo where you have `device1` repeated? `["device1", "device1", "device1"]` – wjandrea Jan 28 '20 at 01:19

1 Answers1

2

Just call json.load with an opened file

import json
with open("package.json") as f:
    data = json.load(f)
print(data)

To traverse folders you can use os.walkdir, this should give you a template to start :)

import json
import sys
import os

def walkrec(root):
    for root, dirs, files in os.walk(root):
        for file in files:
            path = os.path.join(root, file)
            if file.endswith(".json"):
                print(file, end=' ')
                with open(path) as f:
                    data = json.load(f)
                    print(data)


if __name__ == '__main__':
    walkrec(sys.argv[1])
geckos
  • 5,687
  • 1
  • 41
  • 53
  • 1
    [You should always ensure to close your `open()` files:](https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files). "It is good practice to use the with keyword when dealing with file objects. The advantage is that the file is properly closed after its suite finishes, even if an exception is raised at some point." ... "If you’re not using the with keyword, then you should call `f.close()` to close the file and immediately free up any system resources used by it." – felipe Jan 28 '20 at 00:58
  • I updated the question :), thanks for the comment – geckos Jan 28 '20 at 01:01
  • `os.walk` recurses into subdirectories, so why is `walkrec` recursive? – wjandrea Jan 28 '20 at 01:14
  • Oops I have implement this in another language, and just forgot that walk is recursive I will update the answer – geckos Jan 28 '20 at 12:50
  • @geckos Nice -- glad ya got to update it. :) – felipe Jan 28 '20 at 18:14
  • It has to be only one json file, so I need something like: `jdevices = json_data["device"]` --> ['device1', 'device2', 'device3'] and `jstatus = json_data["device\device1\status"]` --> looks for the status of device – JanF Jan 28 '20 at 21:49