Maddy
Maddy

Reputation: 705

How to make JSON array by extracting response from API in Karate

I want to extract some values and store in array in JSON format.

I have my code in karate-config.js file as the API I am calling needs to be called only once and the results needs to be stored in array so it can be later utilized inside other features.

 var result = karate.callSingle('classpath:examples/users.feature@country',config);
 config.array = []
     for (var i=0; i<result.response.length; i++){
          config.array.push({ 'userId': result.response[i].id, 'country': result.response[i].country});
     }
karate.log(config.array)

Results

[object Object],[object Object] 

Expected Results

                [
                    {
                    "userId" : 931,
                    "country" : "USA"
                    },

                    {
                    "userId" : 709,
                    "country" : "HK"
                    }
                ]

Upvotes: 1

Views: 1090

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58058

Even if the log shows like this, the data may be fine - there are some limitations with JSON in JS vs the rest of Karate and Java.

Just add a conversion:

config.array = karate.toJava(config.array);

If it doesn't work, it can be a bug in Karate which you are welcome to contribute a fix for.

Upvotes: 1

Related Questions