Uday T
Uday T

Reputation: 137

Parsing JSON output in Robot framework [Tried most options in the forum]

I have a JSON output like this:

{
   ":output":{
      "response":"{ \"ParentId\" : 125,  \"ParentKey\" : { \"key\" : \"9aqews-uwdguwdw8-9uw8\",                  \"identity\" : \"key_ID=674\" } }"
   }
} 

I'm trying to fetch the content of key, that is: 9aqews-uwdguwdw8-9uw8

Here are somethings that tried:

 ------------------------------------------------------
 ${json_data}    Parse Json    ${output}
 Log    ${json_data["output"]["response"]}
 Log    ${json_data["output"]["response"][0][0:10]}
 ------------------------------------------------------

 ${json}=    Convert To Dictionary    ${values}
 ${j_keys}=    Get Dictionary Keys    ${json}
 Log  ${j_keys}
 ------------------------------------------------------

 ${values}=    Evaluate    json.loads($output)    json
 Log  ${values['output']['response'][1]}
 -----------------------------------------------------

 ${KeySP}=  Get Substring  ${values}  "key" ","
 Log  ${keySP}
 ------------------------------------------------------

  #${parkeydict}=  ${values['output']['response']}
  #${keyspacedict}=   ${parkeydict['ParentKey']}
  #Log  ${keyspacedict['key']}

 ------------------------------------------------------

I have tried several other steps, possibilities and keywords, The best I could parse is till "Log ${json_data["output"]["response"]}" which returns data from 'response'.

It fails even if I convert to Dict and access the 'key', I think that further data after 'response' is completely stored as values.

Can someone help/guide me on how to capture the data in 'key' variable?

Thanks in Advance!

Upvotes: 0

Views: 1675

Answers (1)

Bryan Oakley
Bryan Oakley

Reputation: 386010

The first problem is that you're trying to use ['output'], but the key is :output.

The second problem is that the value of the "response" key is not a dictionary, it's a string that looks like a dictionary. You must convert it to a dictionary before you try to pull values from it, assuming it is indeed an well-formed json dictionary and not just a string that might look like a dictionary.

This works for me on the exact data provided in the question:

${values}=      Evaluate      json.loads($output)
${response}=    Evaluate      json.loads($values[':output']['response'])
${key}=         set variable  ${response['ParentKey']['key']}

should be equal  ${key}  9aqews-uwdguwdw8-9uw8

Note: if you're using a version of robot that is older than 3.2 you'll need to include json as a final argument for the Evaluate command so that robot knows to import the module. Starting with version 3.2 and onward, modules used in the expression are automatically imported.

Upvotes: 3

Related Questions