How do I read a json file into python?

后端 未结 2 1450
半阙折子戏
半阙折子戏 2020-12-22 13:10

I\'m new to JSON and Python, any help on this would be greatly appreciated.

I read about json.loads but am confused

How do I read a file into Python using j

2条回答
  •  生来不讨喜
    2020-12-22 13:48

    Open the file, and get a filehandle:

    fh = open('thefile.json')
    

    https://docs.python.org/2/library/functions.html#open

    Then, pass the file handle into json.load(): (don't use loads - that's for strings)

    import json
    data = json.load(fh)
    

    https://docs.python.org/2/library/json.html#json.load

    From there, you can easily deal with a python dictionary that represents your json-encoded data.

    new_list = [(detail['abc'], detail['def']) for detail in data['details']]
    

    Note that your JSON format is also wrong. You will need comma delimiters in many places, but that's not the question.

提交回复
热议问题