FLAK-ZOSO
FLAK-ZOSO

Reputation: 4088

Python json.py can't convert string to dictionary

I'm trying to put a dictionary into a .txt file, and then using json.load(File.read()) parse the string to a dictionary.

For some reason it is not working.

CODE:

import json
File = open(r"{}.txt".format(path), 'w')
File.write(json.dumps({"Key":"Value"}))
File.close()
#There the .txt file is {'Key':'Value'}
File = open(r"{}.txt".format(path), 'r')
Dictionary = json.loads(File.read())

ERROR:

Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    json.loads(FIle.read())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.1520.0_x64__qbz5n2kfra8p0\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

But when I do this:

>>> json.dumps({"Key":"Value"})
'{"Key": "Value"}'
>>> json.loads('{"Key": "Value"}')
{'Key': 'Value'}
>>>

nothing wents wrong.

Why does it happen? Thank you in advance for answering.

Edit


Thanks a lot for who in the comments suggested me to use json.load(), it worked.

>>> json.load(open(r"C:\\Users\FLAK-ZOSO\Desktop\mlmlm.txt", 'r+'))
{'Key': 'Value'}
>>> Dictionary = json.load(open(r"C:\\Users\WouldYouLikeToKnow\Desktop\mlmlm.txt", 'r+'))
>>> Dictionary
{'Key': 'Value'}

The problem was that the file results empty because before File.close() the edits aren't saved.
Thank you all for helping me.

Upvotes: 0

Views: 1085

Answers (2)

FLAK-ZOSO
FLAK-ZOSO

Reputation: 4088

The json library has more methods than only json.dumps() and json.loads().


  • json.dumps stands for dump-s where s stands for string
  • json.loads stands for load-s where s stands for string

In fact this two methods are returning or passing as parameter a string-type.

>>> json.dumps({1: 'a', 2: 'b'}) #Needs as parameter an object or a value
'{"1": "a", "2": "b"}' #Returns a string
>>> json.loads('{"1": "a", "2": "b"}') #Needs as parameter a string
{'1': 'a', '2': 'b'} #Parses an object or returns a value

  • json.dump writes to a file specified as the second argument (.txt or .json) the first argument passed
  • json.load reads from a file (.txt or .json) passed as the first argument

This two methods are reading or writing to a .json file.

>>> json.dumps({1: 'a'}, open('file.json', 'w+'))
>>> json.load(open('file.json', 'r'))
{'1': 'a'} #Returns an object or a value

So, in order to avoid raising errors, you can avoid doing this:

value = json.loads(open('file.json', 'r').read()) #Shouldn't do this
value = json.load(open('file.json', 'r')) #Much better, more efficient and it doesn't raise any error

Upvotes: 0

Alex Yepifanov
Alex Yepifanov

Reputation: 26

Since I don't have reputation to comment I'm writing this as an answer. I tried to run your erroring code on my machine and it had no problems with it whatsoever (provided I replace path with something like 'check_json.json'). This tells me that it's related to your environment.

The error itself (json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)) seems to pop up when you're operating on an empty string, meaning that File.read() is returning an empty string that json.loads doesn't know what to do with.

Some possible issues could be:

  1. You've redefined a reserved keyword somewhere and so Python is struggling to get the objects to behave as they should (a shot in the dark based on your use of File and Dictionary. Yes they're not builtins/reserved words but who knows what the rest of the code looks like right?)
  2. Something's wrong in your Python install and you need to reinstall it.
  3. You have some sort of strange permissions that stop you from actually saving down data to this file that you're creating.

Upvotes: 1

Related Questions