Reputation: 53
I am trying to get the result using the conversation API of IBM Watson using this code:
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))
Running this code will print this 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
}
I've tried many way but can't decode this JSON. I just want to get the output text: "Hi I am Nao Nice to meet you". How can I do this?
Upvotes: 0
Views: 857
Reputation: 9357
As mentioned by Kevin, you can access individual node segments as follows:
response['output']['text'][0]
Watson conversation response tends to be all connected, so you can use this method.
'<p>'.join(response['output']['text'])
That will embed a HTML paragraph break between each array item and return it as a full string.
Or if you want take action on each object of the output text.
for text in response['output']['text']:
print(text)
Upvotes: 1
Reputation: 76254
Json is a serialization format, which is not intended to be directly interacted with without de-serializing first. Rather than trying to extract information from the json string, just extract it from the dictionary you used to create the json string.
print(response["output"]["text"][0])
Upvotes: 1