0

I'm learning how to use json in python and have encountered this problem: The next two paragraphs are run separately from the same directory:

x=[1,-1,[1]]
import json
f=open('states','w')
f.close()
f=open('states','r+')
json.dump(x,f)
json.dump(x,f)
f.close()

f=open('states','r+')
y=json.load(f)
f.close()
print y

The first part seems to run fine however when i run the second part this error occurs:

ValueError                                Traceback (most recent call last)
<ipython-input-41-e06f9ba74fae> in <module>()
  1 f=open('states','r+')
----> 2 y=json.load(f)
      3 f.close()
      4 print y

C:\Users\Yael\Downloads\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\json\__init__.pyc in load(fp, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    288         parse_float=parse_float, parse_int=parse_int,
    289         parse_constant=parse_constant, object_pairs_hook=object_pairs_hook,
--> 290         **kw)
    291 
    292 

C:\Users\Yael\Downloads\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\json\__init__.pyc in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    336             parse_int is None and parse_float is None and
    337             parse_constant is None and object_pairs_hook is None and not kw):
--> 338         return _default_decoder.decode(s)
    339     if cls is None:
    340         cls = JSONDecoder

C:\Users\Yael\Downloads\WinPython-64bit-2.7.10.2\python-2.7.10.amd64\lib\json\decoder.pyc in decode(self, s, _w)
    367         end = _w(s, end).end()
    368         if end != len(s):
--> 369             raise ValueError(errmsg("Extra data", s, end, len(s)))
    370         return obj
    371 

ValueError: Extra data: line 1 column 13 - line 1 column 25 (char 12 - 24)

Why is this happening? I tried changing x to an int and a float an the same error occurs. Thank you for any help ^^.

2 Answers 2

2

The error is that you dump the JSON twice. So when you want to load it again, it is not well formed. Try to dump only once and retry. Or verify that your JSON is correct in the file you saved.

Sign up to request clarification or add additional context in comments.

Comments

0

I'm learning how to use json in python

Alright, here's some examples.

Write to a file

import json
x=[1,-1,[1]]
with open('states.txt', 'wb') as f:
    json.dump(x, f)

Read from a file

import json
with open('states.txt') as f:
    y = json.load(f)
    print(y) # [1, -1, [1]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.