[Tutor] using json to pass a dict thru a file
Alan Gauld
alan.gauld at btinternet.com
Wed Mar 18 10:22:22 CET 2015
On 17/03/15 22:30, Doug Basberg wrote:
> dataDict = {'Time': None, 'Vbatt': None, 'Ichrg': None, 'Vpanel': None}
>
> vb = 51.25
> ic = 5.89
> vp = 55.78
> i = 0
>
> dataDict['Time'] = tymAsc
> dataDict['Vbatt'] = vb
> dataDict['Ichrg'] = ic
> dataDict['Vpanel'] = vp
>
> fn = 'testData01.dat'
> f = open(fn, 'ab')
I don;t believe json needs a binary file.
Also do you really want to append data?
> for i in xrange(5):
> json.dump(dataDict, f)
> # f.write(str(dataDict))
> # f.write('\n\r')
> tymAsc = t.asctime(t.localtime())
> dataDict['Time'] = tymAsc
> dataDict['Vbatt'] = vb + i
> dataDict['Ichrg'] = ic + i
> dataDict['Vpanel'] = vp + i
> f.close()
> print('*********** done ********** \n\r')
You are effectively creating 5 separate dictionaries in your json file.
> fn = 'testData01.dat'
> f = open(fn, 'r')
> dataDict = json.load(f)
> f.close()
But you only read one back
> Traceback (most recent call last):
> File "C:/Python27/myTestRcv00.py", line 17, in <module>
> dataDict = json.load(f)
> File "C:\Python27\lib\json\__init__.py", line 290, in load
> **kw)
> File "C:\Python27\lib\json\__init__.py", line 338, in loads
> return _default_decoder.decode(s)
> File "C:\Python27\lib\json\decoder.py", line 368, in decode
> raise ValueError(errmsg("Extra data", s, end, len(s)))
> ValueError: Extra data: line 1 column 85 - line 1 column 421 (char 84 - 420)
>>>>
Python is therefore confused.
Try your experiment using just one dictionary in and one dictionary out.
Once you have that working write multiple dictionaries and then read
them back.
Incidentally, you can check the content of your json file by opening
it in a text editor, it is a human readable format.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list