How do I read a json file into python?

后端 未结 2 1462
半阙折子戏
半阙折子戏 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.

    0 讨论(0)
  • 2020-12-22 14:07

    I'm trying to understand your question as best as I can, but it looks like it was formatted poorly.

    First off your json blob is not valid json, it is missing quite a few commas. This is probably what you are looking for:

    {
        "header": {
            "platform": "atm",
            "version": "2.0"
        },
        "details": [
            {
                "abc": "3",
                "def": "4"
            },
            {
                "abc": "5",
                "def": "6"
            },
            {
                "abc": "7",
                "def": "8"
            }
        ]
    }
    

    Now assuming you are trying to parse this in python you will have to do the following.

    import json
    
    json_blob = '{"header": {"platform": "atm","version": "2.0"},"details": [{"abc": "3","def": "4"},{"abc": "5","def": "6"},{"abc": "7","def": "8"}]}'
    json_obj = json.loads(json_blob)
    
    final_list = []
    
    for single in json_obj['details']:
        final_list.append((int(single['abc']), int(single['def'])))
    
    print(final_list)
    

    This will print the following: [(3, 4), (5, 6), (7, 8)]

    0 讨论(0)
提交回复
热议问题