Python无法解码JSON对象 [英] Python No JSON object could be decoded

查看:76
本文介绍了Python无法解码JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JSON方面遇到问题,我似乎无法弄清为什么它不起作用.应该可以输出JSON.

I am having an issue with JSON, I can't seem to figure out why this is not working. This is supposed to output JSON.

这是我的代码

#!/usr/bin/env python
import socket
import struct
import json

def unpack_varint(s):
    d = 0
    i = 0
    while True:
        b = ord(s.recv(1))
        d |= (b & 0x7F) << 7*i
        i += 1
        if not b & 0x80:
            return d

def pack_data(d):
    return struct.pack('>b', len(d)) + d

def pack_port(i):
    return struct.pack('>H', i)

def get_info(host, port=25565):

    # Connect
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect((host, port))

    # Send handshake + status request
    s.send(pack_data("\x00\x00" + pack_data(host.encode('utf8')) + pack_port(port) + "\x01"))
    s.send(pack_data("\x00"))

    # Read response
    unpack_varint(s)     # Packet length
    unpack_varint(s)     # Packet ID
    l = unpack_varint(s) # String length

    d = ""
    while len(d) < l:
        d += s.recv(1024)

    # Close our socket
    s.close()

    # Load json and return
    return json.loads(d.decode('utf8'))
get_info('162.213.43.124');

我收到此错误

Traceback (most recent call last):
  File "main.py", line 46, in 
    get_info('162.213.43.124');
  File "main.py", line 45, in get_info
    return json.loads(d.decode('utf8'))
  File "/usr/local/lib/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/local/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/lib/python2.7/json/decoder.py", line 383, in raw_decode
    raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded

如果有人可以救援,那就太好了!

If anyone could come to the rescue that would be awesome!

推荐答案

似乎您的JSON无效.在这种情况下,这完全取决于服务器发送给您的数据(您未显示).我建议通过 JSON验证程序运行响应.

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

这篇关于Python无法解码JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆