- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-08-2024 05:43 AM
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.
*** Script: Mercedes
*** Script: Mercedes
*** Script: undefined
*** Script: undefined
Please advice.
Thanks,
Sunil Safare
Solved! Go to Solution.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-08-2024 05:55 AM - edited 05-08-2024 06:01 AM
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

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-08-2024 05:55 AM - edited 05-08-2024 06:01 AM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-08-2024 05:56 AM
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
Please mark this response as correct and helpful if it assisted you with your question.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-08-2024 06:04 AM
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:
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