user713927 user713927 - 1 month ago 8
JSON Question

Selenium test, parse Json string from variable

I am using selenium Selenese to do some functional tests.
I need to parse the Json content of the body.
Here is the json:

{"access_token":"ab89978b-
74a1-41a6-81e7-7b520ea9d29f","token_type":"bearer","refresh_token":"38a3a34b-09c9-452e-
b05b-6903770a877f","expires_in":1799,"scope":"read"}


I am using the following Selenese command:

<tr>
<td>store</td>
<td>
javascript{
var jsonstr = '${body}'
var obj=JSON.parse(jsonstr);
var token=obj.access_token;
}
</td>
<td>token</td>
</tr>


But I am getting the following error:


Command execution failure. Please search the user group at https://groups.google.com/forum/#!forum/selenium-users for error details from the log window. The error message is: missing ; before statement


Does anyone know how to parse the content of a variable in selenium that contain Json string?

Answer

You need to use storeEval instead of store

<tr>
    <td>store</td>
    <td>{&quot;access_token&quot;: &quot;ab89978b-74a1-41a6-81e7-7b520ea9d29f&quot;, &quot;token_type&quot;: &quot;bearer&quot;, &quot;refresh_token&quot;: &quot;38a3a34b-09c9-452e-b05b-6903770a877f&quot;, &quot;expires_in&quot;: 1799, &quot;scope&quot;: &quot;read&quot;}</td>
    <td>json</td>
</tr>
<tr>
    <td>echo</td>
    <td>${json}</td>
    <td></td>
</tr>
<tr>
    <td>storeEval</td>
    <td>var x = '${json}'; var obj=JSON.parse(x); obj.access_token;</td>
    <td>bam</td>
</tr>
<tr>
    <td>echo</td>
    <td>${bam}</td>
    <td></td>
</tr>