如何删除输出中的“u”。错误:AttributeError:'dict' 对象没有属性 'encode'

Sha*_*amy 0 python json

我正在尝试将 JSON 输出存储在变量中。最初我得到了输出,但它前面带有字符“u”(unicode)。下面是初始输出:

{u'imdata': [{u'nvoNws': {u'attributes': {u'dn': u'sys/epId-1/nws', u'status': u'', u'persistentOnReload': u'true', u'monPolDn': u'', u'modTs': u'2017-02-24T00:50:47.373+00:00', u'uid': u'0', u'childAction': u''}}}, {u'nvoPeers': {u'attributes': {u'dn': u'sys/epId-1/peers', u'status': u'', u'persistentOnReload': u'true', u'monPolDn': u'', u'modTs': u'2017-02-24T00:50:47.373+00:00', u'uid': u'0', u'childAction': u''}}}, {u'nvoEp': {u'attributes': {u'status': u'', u'operState': u'down', u'persistentOnReload': u'true', u'propFaultBitmap': u'', u'hostReach': u'0', u'adminSt': u'disabled', u'holdUpTime': u'0', u'encapType': u'0', u'uid': u'0', u'epId': u'1', u'sourceInterface': u'unspecified', u'descr': u'', u'monPolDn': u'uni/fabric/monfab-default', u'modTs': u'2017-02-24T00:50:47.373+00:00', u'holdDownTimerExpiryTime': u'NA', u'autoRemapReplicationServers': u'no', u'operEncapType': u'0', u'dn': u'sys/epId-1', u'mac': u'00:00:00:00:00:00', u'cfgSrc': u'0', u'childAction': u'', u'vpcVIPNotified': u'no', u'learningMode': u'0', u'controllerId': u'0', u'holdUpTimerExpiryTime': u'NA', u'holdDownTime': u'180'}, u'children': [{u'nvoPeers': {u'attributes': {u'status': u'', u'persistentOnReload': u'true', u'monPolDn': u'', u'modTs': u'2017-02-24T00:50:47.373+00:00', u'uid': u'0', u'rn': u'peers', u'childAction': u''}}}, {u'nvoNws': {u'attributes': {u'status': u'', u'persistentOnReload': u'true', u'monPolDn': u'', u'modTs': u'2017-02-24T00:50:47.373+00:00', u'uid': u'0', u'rn': u'nws', u'childAction': u''}}}]}}], u'totalCount': u'3'}
Run Code Online (Sandbox Code Playgroud)

然后我添加encode('utf-8')到我的打印输出语句中,之后我得到以下错误:

Traceback (most recent call last):
  File "/Users/shandeep/Desktop/n9k-rest/Andys_payloads/Andys_script.py", line 548, in <module>
    get_interface_nve()
  File "/Users/shandeep/Desktop/n9k-rest/Andys_payloads/Andys_script.py", line 113, in get_interface_nve
    print(x.encode('utf-8'))
  AttributeError: 'dict' object has no attribute 'encode'
Run Code Online (Sandbox Code Playgroud)

下面是定义和函数调用。

def request_get(dn):
    cookie = login_api()
    response = requests.get(url + dn + '?query-target=subtree&rsp-subtree=full', cookies=cookie, verify=False)
    print('Valid response: \n' + response.text)
    return response.json()

def get_interface_nve():
    x = request_get('/api/mo/sys/epId-1.json')
    print('PRINT OUTPUT: \n')
    #print(x)
    print(x.encode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

函数调用:

get_interface_nve()
Run Code Online (Sandbox Code Playgroud)

dsh*_*dsh 8

dict对象没有方法encode()。那是str对象的方法。您看到的文本是 Python 对(unicode)字符串的“repr”表示。您之所以拥有它,是因为您使用了错误的方法将 dict 转换为字符串。

您需要将您的转换dict为 JSON。这是使用没有达到print()repr()str()json为此使用模块。

例如:

x = {u'imdata': [{u'nvoNws': {u'attributes': {u'dn': u'sys/epId-1/nws'}}}]}
json.dump(x, sys.stdout)
Run Code Online (Sandbox Code Playgroud)