2017-05-03 87 views
0

我試圖使用IBM沃森的通話API使用此代碼來獲得結果:我怎樣才能獲得JSON的價值在Python

import json 
from watson_developer_cloud import ConversationV1 
conversation = ConversationV1(
username='******', 
password='*****', 
version='2016-09-20') 
workspace_id = '***' 
response = conversation.message(workspace_id=workspace_id, message_input={ 
'text': 'hi'}) 
print(json.dumps(response, indent=2)) 

運行這段代碼將打印此JSON:

{ 
"intents": [ 
{ 
    "confidence": 1, 
    "intent": "greating" 
} 
], 
"entities": [], 
"context": { 
"conversation_id": "d6952ab6-e27e-4c50-8b90-01f3087bcc0e", 
"system": { 
    "dialog_stack": [ 
    { 
     "dialog_node": "root" 
    } 
    ], 
    "dialog_request_counter": 1, 
    "dialog_turn_counter": 1, 
    "branch_exited": true, 
    "_node_output_map": { 
    "greeting": [ 
     0 
    ] 
    }, 
    "branch_exited_reason": "completed" 
} 
}, 
"input": { 
"text": "hi" 
}, 
"output": { 
    "log_messages": [], 
    "nodes_visited": [ 
    "greeting" 
    ], 
    "text": [ 
    "Hi I am Nao Nice to meet you" 
    ] 
}, 
"alternate_intents": false 
} 

我試過很多方法,但無法解碼這個JSON。我只想得到輸出文字:「你好,我很好,很高興見到你。」我怎樣才能做到這一點?

回答

1

Json是一種序列化格式,如果不首先進行反序列化,它不會直接與之交互。而不是試圖從json字符串中提取信息,只是從您用來創建json字符串的字典中提取它。

print(response["output"]["text"][0]) 
+0

很好<3我的方法是嘗試解碼json.dump數據,所以我不能得到任何東西<3很多謝謝你 –

0

正如凱文提到的,可以訪問各個節點段如下:

response['output']['text'][0] 

沃森會話響應趨於所有連接的,所以可以使用這種方法。

'<p>'.join(response['output']['text']) 

這將在每個數組項目之間嵌入HTML段落中斷並將其作爲完整字符串返回。

或者如果您想對輸出文本的每個對象執行操作。

for text in response['output']['text']: 
    print(text)