【问题标题】:What is causing this JSONDecodeError?是什么导致了这个 JSONDecodeError?
【发布时间】:2018-12-30 20:52:47
【问题描述】:

我正在尝试在 HASSio 中设置 iTunes 媒体播放器。我在我的 Mac 上运行了 REST API,我可以在浏览器中将其拉起并查看它是否正在运行。在 HA 中,我可以调整音量并切换到下一首歌曲,但它不会告诉我当前正在播放什么。以下代码是每当我尝试调整音量、启动/停止、前进/后退时输出到日志的内容。

HASS - 0.84.6

ITUNES - 12.2.1.16

ERROR (MainThread) [homeassistant.components.media_player] Error while setting up platform itunes
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/homeassistant/helpers/entity_platform.py", line 128, in _async_setup_platform
      SLOW_SETUP_MAX_WAIT, loop=hass.loop)
  File "/usr/local/lib/python3.6/asyncio/tasks.py", line 358, in wait_for
      return fut.result()
  File "/usr/local/lib/python3.6/concurrent/futures/thread.py", line 56, in run
      result = self.fn(*self.args, **self.kwargs)
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/media_player/itunes.py", line 169, in setup_platform
      add_entities
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/media_player/itunes.py", line 199, in __init__
      self.update()
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/media_player/itunes.py", line 237, in update
      now_playing = self.client.now_playing()
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/media_player/itunes.py", line 92, in now_playing
      return self._request('GET', '/now_playing')
  File "/usr/local/lib/python3.6/site-packages/homeassistant/components/media_player/itunes.py", line 80, in _request
      return response.json()
  File "/usr/local/lib/python3.6/site-packages/requests/models.py", line 897, in json
      return complexjson.loads(self.text, **kwargs)
  File "/usr/local/lib/python3.6/site-packages/simplejson/__init__.py", line 518, in loads
      return _default_decoder.decode(s)
  File "/usr/local/lib/python3.6/site-packages/simplejson/decoder.py", line 370, in decode
      obj, end = self.raw_decode(s)
  File "/usr/local/lib/python3.6/site-packages/simplejson/decoder.py", line 400, in raw_decode
      return self.scan_once(s, idx=_w(s, idx).end())
simplejson.errors.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

这是itunes.py的第66-171行

def _request(self, method, path, params=None):
    """Make the actual request and return the parsed response."""
    url = '{}{}'.format(self._base_url, path)

    try:
        if method == 'GET':
            response = requests.get(url, timeout=DEFAULT_TIMEOUT)
        elif method == 'POST':
            response = requests.put(url, params, timeout=DEFAULT_TIMEOUT)
        elif method == 'PUT':
            response = requests.put(url, params, timeout=DEFAULT_TIMEOUT)
        elif method == 'DELETE':
            response = requests.delete(url, timeout=DEFAULT_TIMEOUT)

        return response.json()
    except requests.exceptions.HTTPError:
        return {'player_state': 'error'}
    except requests.exceptions.RequestException:
        return {'player_state': 'offline'}

def _command(self, named_command):
    """Make a request for a controlling command."""
    return self._request('PUT', '/' + named_command)

def now_playing(self):
    """Return the current state."""
    return self._request('GET', '/now_playing')

def set_volume(self, level):
    """Set the volume and returns the current state, level 0-100."""
    return self._request('PUT', '/volume', {'level': level})

def set_muted(self, muted):
    """Mute and returns the current state, muted True or False."""
    return self._request('PUT', '/mute', {'muted': muted})

def play(self):
    """Set playback to play and returns the current state."""
    return self._command('play')

def pause(self):
    """Set playback to paused and returns the current state."""
    return self._command('pause')

def next(self):
    """Skip to the next track and returns the current state."""
    return self._command('next')

def previous(self):
    """Skip back and returns the current state."""
    return self._command('previous')

def stop(self):
    """Stop playback and return the current state."""
    return self._command('stop')

def play_playlist(self, playlist_id_or_name):
    """Set a playlist to be current and returns the current state."""
    response = self._request('GET', '/playlists')
    playlists = response.get('playlists', [])

    found_playlists = \
        [playlist for playlist in playlists if
         (playlist_id_or_name in [playlist["name"], playlist["id"]])]

    if found_playlists:
        playlist = found_playlists[0]
        path = '/playlists/' + playlist['id'] + '/play'
        return self._request('PUT', path)

def artwork_url(self):
    """Return a URL of the current track's album art."""
    return self._base_url + '/artwork'

def airplay_devices(self):
    """Return a list of AirPlay devices."""
    return self._request('GET', '/airplay_devices')

def airplay_device(self, device_id):
    """Return an AirPlay device."""
    return self._request('GET', '/airplay_devices/' + device_id)

def toggle_airplay_device(self, device_id, toggle):
    """Toggle airplay device on or off, id, toggle True or False."""
    command = 'on' if toggle else 'off'
    path = '/airplay_devices/' + device_id + '/' + command
    return self._request('PUT', path)

def set_volume_airplay_device(self, device_id, level):
    """Set volume, returns current state of device, id,level 0-100."""
    path = '/airplay_devices/' + device_id + '/volume'
    return self._request('PUT', path, {'level': level})


def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up the iTunes platform."""
add_entities([
    ItunesDevice(
        config.get(CONF_NAME),
        config.get(CONF_HOST),
        config.get(CONF_PORT),
        config.get(CONF_SSL),

        add_entities
    )
])

【问题讨论】:

  • 打印 /now_playing 的内容 - 它不是有效的 JSON,这就是解码器抱怨的原因。
  • ;你有 JSONLines 格式。它在第二行的第一个字符上失败了,这是一个不错的指标。
  • 无论如何,如果问题中没有包含无效 JSON 的内容,我们应该如何知道为什么它不是有效的 JSON? (roganjosh 的猜测可靠的,但问题不完整)。
  • 我们不是要求更多代码,我们要求的是一小部分假定的 JSON 内容
  • (...嗯,一小部分,但足够完整,无法以相同的方式解析失败,如minimal reproducible example 指南中所述——同样,问题应该只包括 最短的 代码在解析 JSON 时失败并出现完全相同的错误——理想情况下,简化为根本不做任何与 web-server / web-request 相关的事情,如果您可以通过硬编码的内容生成相同的问题无法解析为字符串;请密切注意该规范的“最小”和“完整”/“可验证”部分)。

标签: python json python-3.x itunes simplejson


【解决方案1】:

Mac OS Sierra 仅随 Python 2.XX 一起安装。升级到 Python 3.6X 似乎可以正常工作。

【讨论】:

    猜你喜欢
    • 2019-07-01
    • 2011-02-12
    • 2011-11-27
    • 2015-09-08
    • 2012-01-22
    • 1970-01-01
    • 2012-01-29
    • 2014-11-07
    相关资源
    最近更新 更多