Ajay Bhagchandani
Ajay Bhagchandani

Reputation: 145

Getting json.decoder.JSONDecodeError: Expecting value: line 1 column 1

Code:

def get_result(response_path):
  response_s3_path = re.sub(config.path_prefix,'',response_path).strip('/')
  print('== response_s3_path')
  print(response_s3_path)
  response_local_path = download_file_from_s3(response_s3_path)
  print('== response_local_path')
  print(response_local_path)
  if response_local_path==-1:
      print('Failed to open response_local path')
      return -1

  with open(response_local_path, 'r') as f:
      print(type(json.load(f)))
      print(json.load(f))

      if isinstance(json.load(f), str):
          response = json.loads(json.load(f))
            #response = json.load(f)
      elif isinstance(json.load(f), dict):
          print('json.loads(dict)')
          response = json.load(f)

Output of the inserted print statements:

== response_s3_path
AAAA/XXXX/response.json
== response_local_path
./tmp/response.json
<class 'dict'>
{'success': True, 'message': 'Device detected', 'data': {'areas': 2, 'num': 43, 'probability_x': 0.8843076229095459, 'probability_n-x': 0.9764912003694579, 'grids': [ [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]], 'test123': False, 'deviceDetected': True, 'unique_file_index': 'xxxx', 'sensorLogURL': 'https://xxxxx/'}}

Error message post the output:

  File "/Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/AjayB/Desktop/Python/crackd/misc/training_apis/training_apis_server/Apis/views.py", line 1141, in get_inference_results_api
    _, inference_array = get_inference_results_from_df(df_pass)
  File "/Users/AjayB/Desktop/Python/crackd/misc/training_apis/training_apis_server/Apis/views.py", line 1260, in get_inference_results_from_df
    inference_array = get_inference_array(inference_links)
  File "/Users/AjayB/Desktop/Python/crackd/misc/training_apis/training_apis_server/Apis/views.py", line 721, in get_inference_array
    final_response_params = get_result(obj_tmp['response']['path'])
  File "/Users/AjayB/Desktop/Python/crackd/misc/training_apis/training_apis_server/Apis/views.py", line 644, in get_result
    print(isinstance(json.load(f), dict))
  File "/Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/json/__init__.py", line 299, in load
    parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
  File "/Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/json/__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "/Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/json/decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/Users/AjayB/anaconda3/envs/MyDjangoEnv/lib/python3.6/json/decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
[08/Nov/2019 05:49:38] "POST /list/inference_history/ HTTP/1.1" 500 147054

Failing to understand that if the json.load(f) has class 'dict', and on printing, if it seems to be a valid dictionary, then why is it giving me JsonDecodeError on the line:

elif isinstance(json.load(f), dict):?

Please help.

Upvotes: 0

Views: 211

Answers (2)

Ajay Bhagchandani
Ajay Bhagchandani

Reputation: 145

Yes, this worked for me.

  with open(response_local_path, 'r') as f:
      resp = json.load(f)
      if isinstance(resp, str):
          response = json.loads(resp)

      elif isinstance(resp, dict):
          response = resp
      else:
          print(type(resp))

No more using json.load(f) multiple times.

Upvotes: 0

deceze
deceze

Reputation: 522081

You're doing json.load(f) multiple times. f here is a file object which remembers its read location. Once you've loaded the JSON once, the file pointer will be at the end of the file. Trying to read from it again will cause it to return no value unless you rewind it, resulting in the displayed error.

Don't load the file more than once, it's very wasteful too. Do it exactly once:

with open(response_local_path, 'r') as f:
    data = json.load(f)

print(data)

Use data henceforth instead of repeating json.load(f).

Upvotes: 1

Related Questions