Convert string to JSON and fetch its variable

Deepika Mishra
Mega Guru

On doing a GlideAjax I am getting a String written in JSON format.

var str ="var data = {"value1": "abc","value2": "def","value3": "ghi"};";

Now from this string I want to fetch individual parameters from this data variable and get output of individual.

Value1 =  abc
Value2 = def
Value3 = ghi

Please let me know how from the output string which has a variable declaration of var data, I can get my individual output.

 

1 ACCEPTED SOLUTION

var str='var data = {"value":"abc","value2":"def","value3":"ghi"};';

var start=str.indexOf('{');
var end=str.indexOf('}');
var str=str.substring(start,end+1)

gs.info(str)

var data=JSON.parse(str); // Now you will have a valid JSON String

 

//Now access them as below

gs.info(data.value);// Now data.value1 will hold "abc";
gs.info(data.value2);// Now data.value2 will hold "def";
gs.info(data.value3);// Now data.value2 will hold "ghi";

 

Its my bad i additionaly added the parsing statement twice;

please try the above cod. its tested 

View solution in original post

22 REPLIES 22

Ankur Swami
Tera Guru

Hi,

You can simply get the object values by objectName.Variable name.

EX: data.value1

See below Screenshot:

find_real_file.png

 

OUTPUT:

 

find_real_file.png

 

Please mark correct answer if it helps

 

Thanks,

Ankur

Hi Ankur,

I am getting the entire thing as a string

String: "var data = { "value1": "abc", "value2": "def", "value3": "ghi" };"

from here I want to convert it to JSON and then extract.

So please tell me how to first convert this to JSON

Hi,

You can convert string data to JSON by using the below example:

 

JSON.parse('{"value1":"John", "age":30, "city":"New York"}');
 
For your given example use like below:
 
gs.print(JSON.parse(' { "value1": "abc", "value2": "def", "value3": "ghi" }'));
 
This will return 
[object] [object] if you print in the background script, Which will be a JSON object.
 
Thanks,
Ankur
 
 

Hi,

 

You can convert only ({"value1": "abc","value2": "def","value3": "ghi"}) to the JSON.

Not like given by you, So use the code like below:

 

 

var str ='var data = {"value1": "abc","value2": "def","value3": "ghi"};';
var js_data = str.split('= ');
var js_data1 = js_data[1].split(';');
gs.print(JSON.parse(js_data1[0]));