views:

42

answers:

2

Using R, I generate a list that contains certain unquoted elements. Please see at the bottom- it is invalid javascript code.

R code (does not work)

outq <- lapply (out, function (el){
 el <- if( is.factor(el$ann) ){ 
 el$ann <- apply(el$ann, 1, function(e){   e <- paste('"', e, '"', sep="") })
 }   
}) 

In the R language, How can I quote the members of the list$x$ann factor?

When I try to parse this JSON, json2.js fails.

Sample Data (Invalid JSON)

results = JSON.parse(
{
 "result": {
 "tot": {
 "molal": [ 0.00071243, 0.00071243,      4,      4 ],
   "ann": [ , , ,  ] 
},
   "desc": {
 "val": [ 8.3486,      4, 0.8531, 4.0025, 0.99999, 0.00072541, 0.00071243,    100, -1.2983e-05, -0.00016223,     17, 111.02, 55.511 ],
   "ann": [ Charge balance, Adjusted to redox eq, , , , , , , , , , ,  ] 
},
   "species": {
 "molal": [ 55.508, 0.00029101, 2.3071e-09, 0.00042017, 0.00028731, 4.4532e-06, 4.9292e-07, 0.00069149, 1.0274e-05, 6.2142e-06, 4.9139e-12,      4,      0, 4.1166e-27,      4, 8.5144e-21 ],
   "act": [ 0.8531, 0.00010921, 4.4812e-09, 1.4857e-06, 7.7889e-05, 4.4532e-06, 9.6777e-07, 0.00024834, 3.3916e-06, 0.00028204, 4.9139e-12, 2.2702,      0, 4.1166e-27, 3.7925, 1.8453e-20 ] 
},
   "master": {
 "molal": [ 0.00071243, 0.00071243,      4, 8.2332e-27,      4, 1.7029e-20 ] 
},
   "pphases": {
 "moles": 9.9993,
   "delta": -0.00071243 
},
   "ListInfo": {
 "n": 1,
   "format": true 
} 
} 
}
);
+1  A: 

Is there a reason you cannot use the RJSON / RJSONIO packages for R ?

Dirk Eddelbuettel
I *am* using RJSONIO, but it does not quote the factor(s).
knb
Well, you didn't say, or I overlooked it. Factors are an R construct, so you may have to convert via `as.character()`.
Dirk Eddelbuettel
since version 0.3.1, library RJSONIO also quotes the JSON representation of factor variables.
knb
Thanks for the update. Good to know it now deals with factors properly.
Dirk Eddelbuettel
A: 

I have advanced a step forward using this R code:

outq <- lapply (out, function (el){el <- if( is.factor(el$ann) ){ el$ann <- lapply(el$ann, function(e){   e <- paste('"', e, '"', sep="") })} else {el}})  
knb
knb
As Dirk said : el$ann <- as.character(el$ann) and then you can proceed normally.
Joris Meys