Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to read a JSON file so that I can get its values. I have a folder with the JSON's archives. Kindly refer to the below code:

# -*- encoding: utf-8 -*-

from pprint import pprint

import json

import os 

def start():

    for dirname, dirnames, filenames in os.walk('test'):

        for filename in filenames:

            json_file = open(os.path.join(dirname, filename)).read()

            # json_file = unicode(json_file, 'utf-8')

            json_data = json.loads(json_file)

           pprint(json_data)

            for key, value in json_data.items():

                print "KEY : ", key

                print "VALUE: ", value

                start()

Below is one of the JSON's format:

{ "test" : "Search User 1",

   "url"  : "http://127.0.0.1:8000/api/v1/user/1/?format=json",

   "status_code" : 200,

   "method" : "get"

}

But when I try to run the above, what I am getting is an error message:

ValueError: No JSON object could be decoded

I have also tried in the below way:

from pprint import pprint

import json

import os

for dirname, dirnames, filenames in os.walk('test'):

    for filename in filenames:

        json_file_contents = open(os.path.join(dirname, filename)).read()

        try:

            json_data = json.loads(json_file_contents)

        except ValueError, e:

            print e

            print "ERROR"

I can't see any error '-':

for filename in filenames:

        with open(os.path.join(dirname,filename)) as fd:

            json_data = fd.read()

            print json_data

1 Answer

0 votes
by (108k points)

I think that the .read() function is moving the cursor to the end of the file. Try the below code:

for filename in filenames:

    with open(os.path.join(dirname,filename)) as fd:

        json_data = json.load(fd)

For more information regarding Python, you can refer to the Python certification course. 

Browse Categories

...