Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON ValueError: Unterminated string

My script work, but sometimes crashes with that error:

Traceback (most recent call last):
  File "planetafm.py", line 6, in <module>
    songs = json.loads(json_data)
  File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Unterminated string starting at: line 1 column 32 (char 31)

For example, that json causes:

rdsData({"now":{"id":"0052-55","title":"Summertime Sadness (Radio Mix)","artist":"Lana Del Rey","startDate":"2014-09-07 21:48:51","duration":"2014-09-07 21:48:51"}})

sourcecode:

import requests, json, re

url = "http://rds.eurozet.pl/reader/var/planeta.json"
response = requests.get(url)
json_data = re.match('rdsData\((.*?)\)', response.content).group(1)
songs = json.loads(json_data)
print (songs['now']['artist'] + " - " + songs['now']['title']).encode('utf-8')

Why that json is invalid? How to fix this?
Thanks for answers!

like image 938
CodeNinja Avatar asked Sep 05 '26 14:09

CodeNinja


1 Answers

Your regexp has a problem with closing bracket inside text. You can fix it by adding $ to the regexp:

import requests, json, re

url = "http://rds.eurozet.pl/reader/var/planeta.json"
response = requests.get(url)
print response.content
json_data = re.match('rdsData\((.*?)\)$', response.content).group(1)
print json_data
songs = json.loads(json_data)
print (songs['now']['artist'] + " - " + songs['now']['title']).encode('utf-8')
like image 164
Alex Dvoretsky Avatar answered Sep 07 '26 05:09

Alex Dvoretsky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!