类型名称和字段名称只能包含字母数字字符和下划线

时间:2017-08-21 19:44:09

标签: python python-2.7

来自服务器的JSON响应是dict。然后我将JSON字符串转换为namedtuple,以便可以像对象而不是dicts一样访问响应值。

但是,其中一个键包含一个超级(' - '),例如' www-head',显示以下错误:

  

类型名称和字段名称只能包含字母数字字符和下划线

我正在使用python2.7

def __json_object_hook(self, d):
    """function to customized the json.loads to return named tuple instead
    of a dict"""
    return namedtuple('response', d.keys())(*d.values())
def __json2obj(self, data):
    """Helper function which converts the json string into a namedtuple
    so the reponse values can be accessed like objects instead of dicts"""
    return json.loads(data, object_hook=self.__json_object_hook)
def send(self, command):
    """
    Returns:
        response (dict) - The JSON response from the Server as a dict
    """
    cmd = json.dumps(command)
    cmd = "{:04d}".format(len(cmd)) + cmd
    msg_length = len(cmd)

    # make the first time connection
    if not self.firstDone:
        self.__connect()
        self.firstDone = True

    # Send the message to the server
    totalsent = 0
    while totalsent < msg_length:
        try:
            sent = self.sock.send(cmd[totalsent:])
            totalsent = totalsent + sent
        except socket.error as e:
            self.__connect()

    # Check and recieve the response if available
    parts = []
    resp_length = 0
    recieved = 0
    done = False
    while not done:
        part = self.sock.recv(1024)
        if part == "":
            #Socket connection broken, read empty.
            self.__connect()
            #Reconnected to socket.

        # Find out the length of the response
        if len(part) > 0 and resp_length == 0:
            resp_length = int(part[0:4])
            part = part[4:]

        # Set Done flag
        recieved = recieved + len(part)
        if recieved >= resp_length:
            done = True

        parts.append(part)

    response = "".join(parts)
    # return the JSON as a namedtuple object
    return self.__json2obj(response)

现在,我如何将密钥用作字段名称?

0 个答案:

没有答案