3

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 ?

irfan mike
  • 117
  • 2
  • 15

1 Answers1

3

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 }]
Peter Thomas
  • 54,465
  • 21
  • 84
  • 248
  • 1
    May be it's worth mention that the [~~](http://rocha.la/JavaScript-bitwise-operators-in-practice) is a double bitwise operator and behaves like `Math.floor()`. So, it's a JavaScript and not a Karate feature.. ;-) – Peter Jun 13 '19 at 13:58