Reading JSON from a file?

前端 未结 7 2009
無奈伤痛
無奈伤痛 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:50

    This works for me.

    json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.

    Suppose JSON file is like this:

    {
       "emp_details":[
                     {
                    "emp_name":"John",
                    "emp_emailId":"john@gmail.com"  
                      },
                    {
                     "emp_name":"Aditya",
                     "emp_emailId":"adityatest@yahoo.com"
                    }
                  ] 
    }
    
    
    
    import json 
    
    # Opening JSON file 
    f = open('data.json',) 
    
    # returns JSON object as  
    # a dictionary 
    data = json.load(f) 
    
    # Iterating through the json 
    # list 
    for i in data['emp_details']: 
        print(i) 
    
    # Closing file 
    f.close()
    
    #Output:
    {'emp_name':'John','emp_emailId':'john@gmail.com'}
    {'emp_name':'Aditya','emp_emailId':'adityatest@yahoo.com'}
    

提交回复
热议问题