Reading JSON from a file?

前端 未结 7 1845
無奈伤痛
無奈伤痛 2020-11-22 03:33

I am getting a bit of headache just because a simple looking, easy statement is throwing some errors in my face.

I have a json file called strings.json like this:

7条回答
  •  失恋的感觉
    2020-11-22 03:38

    In python 3, we can use below method.

    Read from file and convert to JSON

    import json
    from pprint import pprint
    
    # Considering "json_list.json" is a json file
    
    with open('json_list.json') as fd:
         json_data = json.load(fd)
         pprint(json_data)
    

    with statement automatically close the opened file descriptor.


    String to JSON

    import json
    from pprint import pprint
    
    json_data = json.loads('{"name" : "myName", "age":24}')
    pprint(json_data)
    

提交回复
热议问题