Accessing Json object with array elements

Sunil25
Mega Guru

Hello Experts,

 

I want to access the JSON with the help of arrays, but i am able to access only first element. I have tried this in background script and not able to understand the issue.

 

var inp = {"first car":"Mercedes","second car":"Toyota","third car":"Porsche"};
var type = "first car, second car, third car";

gs.print(inp["first car"]);

var arr = type.split(",");
for (var i=0;i<arr.length;i++){
gs.print(inp[arr[i]]);
}
 
Result::
*** Script: Mercedes
*** Script: Mercedes
*** Script: undefined
*** Script: undefined

Please advice.

 

Thanks,

Sunil Safare

1 ACCEPTED SOLUTION

Muhammed Medni
Tera Guru

Hi @Sunil25 

Can you try this script

 

var inp = {"first car": "Mercedes", "second car": "Toyota", "third car": "Porsche"};
var type = "first car,second car,third car";

gs.print(inp["first car"]);

var arr = type.split(",");
for (var i = 0; i < arr.length; i++) {
    gs.print(inp[arr[i].trim()]); 
}

 

and if you want to print  Key: Value

you can use in the loop

var key = arr[i].trim(); 
gs.print("Key: " + key + ", Value: " + inp[key]);

View solution in original post

3 REPLIES 3

Muhammed Medni
Tera Guru

Hi @Sunil25 

Can you try this script

 

var inp = {"first car": "Mercedes", "second car": "Toyota", "third car": "Porsche"};
var type = "first car,second car,third car";

gs.print(inp["first car"]);

var arr = type.split(",");
for (var i = 0; i < arr.length; i++) {
    gs.print(inp[arr[i].trim()]); 
}

 

and if you want to print  Key: Value

you can use in the loop

var key = arr[i].trim(); 
gs.print("Key: " + key + ", Value: " + inp[key]);

vermaamit16
Kilo Patron

Hi @Sunil25 

 

Change the code as below :

 

var inp = {"first car":"Mercedes","second car":"Toyota","third car":"Porsche"};
var type = "first car, second car, third car";

gs.print(inp["first car"]);

var arr = type.split(",");
for (var i=0;i<arr.length;i++){
gs.print(inp[arr[i].trim()]);
}

 

It was due to whitespace which we removed using trim() method.

 

Thanks and Regards

Amit Verma

Thanks and Regards
Amit Verma

Robbie
Kilo Patron

Hi @Sunil25,

 

You're on the right track, however you need to cater for the white spaces between the comma's and words following these comma's. There's a method called .trim() that can do this for you.

 

Use the below syntax to resolve this:

 

var inp = {"first car":"Mercedes","second car":"Toyota","third car":"Porsche"};
var type = "first car, second car, third car";

gs.print(inp["first car"]);

var arr = type.split(",");
for (var i=0;i<arr.length;i++){
gs.print(inp[arr[i].trim()]);
}
 

To help others (or for me to help you more directly), please mark this response correct by clicking on Accept as Solution and/or Kudos.

 

Thanks, Robbie