cylondude
cylondude

Reputation: 1888

How do I write a json array from R that has a sequence of lat and long?

How do I write a json array from R that has a sequence of lat and long?

I would like to write:

[[[1,2],[3,4],[5,6]]]

the best I can do is:

toJSON(matrix(1:6, ncol = 2, byrow = T))
#"[ [ 1, 2 ],\n[ 3, 4 ],\n[ 5, 6 ] ]"

How can I wrap the thing in another array (the json kind)? This is important to me so I can write files into a geojson format as a LineString.

Upvotes: 5

Views: 126

Answers (2)

agstudy
agstudy

Reputation: 121608

I usually use fromJSON to get the target object :

ll <- fromJSON('[[[1,2],[3,4],[5,6]]]')

str(ll)
List of 1
 $ :List of 3
  ..$ : num [1:2] 1 2
  ..$ : num [1:2] 3 4
  ..$ : num [1:2] 5 6

So we should create , a list of unnamed list, each containing 2 elements:

 xx <- list(setNames(split(1:6,rep(1:3,each=2)),NULL))
identical(toJSON(xx),'[[[1,2],[3,4],[5,6]]]')
[1] TRUE

Upvotes: 5

akrun
akrun

Reputation: 887741

If you have a matrix

 m1 <- matrix(1:6, ncol=2, byrow=T)

may be this helps:

 library(rjson)
 paste0("[",toJSON(setNames(split(m1, row(m1)),NULL)),"]")
 #[1] "[[[1,2],[3,4],[5,6]]]"

Upvotes: 0

Related Questions