+4 votes
in Programming Languages by (74.2k points)
How can I read a JSON file using Python?

1 Answer

+1 vote
by (349k points)
selected by
 
Best answer

Python 'JSON' module provides function load() which you can use to load a file object. You can use the output of load() to access elements of the JSON data.

My JSON file 'fltest.json' has the following contents.

{"widget": {
    "debug": "on",
    "window": {
        "title": "Sample Konfabulator Widget",
        "name": "main_window",
        "width": 500,
        "height": 500
    },
    "image": {
        "src": "Images/Sun.png",
        "name": "sun1",
        "hOffset": 250,
        "vOffset": 250,
        "alignment": "center"
    },
    "text": {
        "data": "Click Here",
        "size": 36,
        "style": "bold",
        "name": "text1",
        "hOffset": 250,
        "vOffset": 100,
        "alignment": "center",
        "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
    }
}}
 

The python code to get the contents of the above file is as follows:

import json
with open('fltest.json', 'r') as f:
    x = json.load(f)
    print(x['widget']['text'])

The above code will print the following:

{'data': 'Click Here', 'size': 36, 'style': 'bold', 'name': 'text1', 'hOffset': 250, 'vOffset': 100, 'alignment': 'center', 'onMouseUp': 'sun1.opacity = (sun1.opacity / 100) * 90;'}

Related questions


...