How to extract array elements from JSON in scala.js

1,125 views
Skip to first unread message

ayush mishra

unread,
Aug 31, 2014, 1:30:01 AM8/31/14
to scal...@googlegroups.com
Hello Guys,

I am new to scala.js and developing a sample project in scala.js. I am stuck while parsing a json.

Here is the sample JSON:-

var json = {"code":200,"employee":[{"id":721,"salary":"50000"}]}

I am able to get "code" from above json but not able to get "employee.id" in scala.js

In javascript, I am able to do this. Here is javascript code:-

var result = JSON.parse(json)

var id = result.employee[0].id

In scala.js. I am trying in the following way:-

val result = JSON.parse(json)

val code = result.code

val id = result.employee[0].id

Here I am getting compilation error :- "identifier expected but integer literal found."

I would greatly appreciate any help.

Regards,
Ayush

Benjamin Jackman

unread,
Aug 31, 2014, 4:59:07 AM8/31/14
to scal...@googlegroups.com
Scala doesn't have [] for array access instead it looks like a method call:

val id = result.employee(0).id

However that isn't going work with the js.dynamic type, since the ScalaJs plugin 
will emit js code that calls employee as though it is a function.

For situations like there there is an annotation that can be added in the library code called
"@JSBracketAccess" this will instruct ScalaJs to emit calls using brackets.

You will need to cast your employee array to a JsArray to be able to use this feature:

val id = result.employee.asInstanceOf[js.Array[js.Dynamic]](0).id

fyi I didn't test this so I hope I wrote it up right.

ayush mishra

unread,
Aug 31, 2014, 5:26:44 AM8/31/14
to scal...@googlegroups.com

Hi Benjamin,

Thanks a lot. It worked!. 

Regards,
Ayush
Reply all
Reply to author
Forward
0 new messages