errors with json.loads
Bill
BILL_NOSPAM at whoknows.net
Wed Sep 20 18:58:54 EDT 2017
Interesting problem, John.
I have probably even less experience with json than you do, so I'm
taking this as an opportunity to learn with you.
Suggestions:
1. Try your example with Python 2 rather than Python 3.
2. Take your file and make it into a string literal in your program, and
try calling json.loads with that as an argument.
Share with us what happens!
Good luck,
Bill
john polo wrote:
> Greetings,
>
> I am using IPython 6.1.0 with Python 3.6.2 on a Windows 7 machine. I
> am not a programmer. I am using a book called Python Data Analytics to
> try to learn some of Python. I am at a section for reading and writing
> JSON data. The example JSON file is:
>
>
> Listing 5-13. books.json
> [{"writer": "Mark Ross",
> "nationality": "USA",
> "books": [
> {"title": "XML Cookbook", "price": 23.56},
> {"title": "Python Fundamentals", "price": 50.70},
> {"title": "The NumPy library", "price": 12.30}
> ]
> },
> {"writer": "Barbara Bracket",
> "nationality": "UK",
> "books": [
> {"title": "Java Enterprise", "price": 28.60},
> {"title": "HTML5", "price": 31.35},
> {"title": "Python for Dummies", "price": 28.00}
> ]
> }]
>
> and the example code for reading the file is:
>
> >>> file = open('books.json','r')
> >>> text = file.read()
> >>> text = json.loads(text)
>
> When I use those 3 lines, I get the following:
>
> JSONDecodeError Traceback (most recent call
> last)
> <ipython-input-22-7aafd41f326e> in <module>()
> ----> 1 text = json.loads(text)
>
> c:\users\..\python\python36\lib\json\__init__.py in loads(s, encoding,
> cls, object_hook, parse_float, parse_int, parse_constant,
> object_pairs_hook, **kw)
> 352 parse_int is None and parse_float is None and
> 353 parse_constant is None and object_pairs_hook is
> None and not kw):
> --> 354 return _default_decoder.decode(s)
> 355 if cls is None:
> 356 cls = JSONDecoder
>
> c:\users\..\python\python36\lib\json\decoder.py in decode(self, s, _w)
> 337
> 338 """
> --> 339 obj, end = self.raw_decode(s, idx=_w(s, 0).end())
> 340 end = _w(s, end).end()
> 341 if end != len(s):
>
> c:\users\..\python\python36\lib\json\decoder.py in raw_decode(self, s,
> idx)
> 353 """
> 354 try:
> --> 355 obj, end = self.scan_once(s, idx)
> 356 except StopIteration as err:
> 357 raise JSONDecodeError("Expecting value", s,
> err.value) from None
>
> JSONDecodeError: Expecting ':' delimiter: line 5 column 50 (char 161)
>
> ?json.loads says that the method is for deserializing "s", with "s"
> being a string, bytes, or bytearray.
>
> In [24]: type(text)
> Out[24]: str
>
> So "text" seems to be a string. Why does json.loads return an error?
>
>
> John
>
More information about the Python-list
mailing list