irfan mike
irfan mike

Reputation: 117

Reading csv file converts it to json but it takes every row in it as a string in karate

I am able to read a csv file and convert it to json by

def expectedResponse = read('classpath:somefile.csv')

Suppose I have csv file as below

name,age
praveen,29
joseph,20

1.It is converting all elements as string and stores in the variable as json. How to keep the number as a number ? because it causes match failure which i do later with the actual response.

2.How to get the value 20. Like by specifying joseph, I want to get the age. I got the jsonpath as

get expectedResponse $.[?(@.member == '<name>')].age

I get the name from examples. So I get it as joseph in runtime. But i get error as reason: not equal (Integer : JSONArray). It is not returning the age alone (Integer value)

Or is there any better way to get it ?

Upvotes: 3

Views: 1743

Answers (1)

Peter Thomas
Peter Thomas

Reputation: 58058

The CSV format does not contain any type information, so everything defaults to "string" and you have to convert it yourself. But this is easy using karate.map().

* text users =
"""
name,age
praveen,29
joseph,20
"""
* csv users = users
* match users == [{ name: 'praveen', age: '29' }, { name: 'joseph', age: '20' }]
* def fun = function(x){ x.age = ~~x.age; return x }
* def users = karate.map(users, fun)
* match users == [{ name: 'praveen', age: 29 }, { name: 'joseph', age: 20 }]

also refer: https://stackoverflow.com/a/78673358/143475

Upvotes: 3

Related Questions