Error: Invalid Json Object

Error: Invalid Json Object

I tried to run this query and keep having this error:

install.packages(“mongolite”)
library(mongolite)

m <- mongo(db = "ionmom")
m6 <- m$aggregate('[{"$unwind":"$cdr"}, {$lookup:{from: "inventory", localField: "_id", foreignField: "_id", as:"inventory"}},{$unwind: "$inventory"}, {"$project":{ "$project": {"cdr.duration": 1, "inventory.wearables.type":1, "inventory.wearables.status":1, "inventory.wearables.battery":1 }}}]')

# Error: Invalid JSON object: [{"$unwind":"$cdr"}, {$lookup:{from: "inventory", localField: "_id", foreignField: "_id", as:"inventory"}},{$unwind: "$inventory"}, {"$project":{ "$project": {"cdr.duration": 1, "inventory.wearables.type":1, "inventory.wearables.status":1, "inventory.wearables.battery":1 }}}]

2 Answers

mongolite uses jsonlite under the hood to do the JSON parsing. If you put your query through jsonlite::fromJSON() you'll see the issue

js <- '[{"$unwind":"$cdr"}, {$lookup:{from: "inventory", localField: "_id", foreignField: "_id", as:"inventory"}},{$unwind: "$inventory"}, {"$project":{ "$project": {"cdr.duration": 1, "inventory.wearables.type":1, "inventory.wearables.status":1, "inventory.wearables.battery":1 }}}]'

jsonlite::fromJSON(js)

# Error: lexical error: invalid char in json text.
#                  [{"$unwind":"$cdr"}, {$lookup:{from: "inventory", loc
#                      (right here) ------^

This is telling you the JSON structure is invalid, because it's expecting quotes " " around each string

js <- '[{"$unwind":"$cdr"}, {"$lookup":{"from": "inventory", "localField": "_id", "foreignField": "_id", "as":"inventory"}},{"$unwind": "$inventory"}, {"$project":{ "$project": {"cdr.duration": 1, "inventory.wearables.type":1, "inventory.wearables.status":1, "inventory.wearables.battery":1 }}}]'

m$aggregate(js)

## I don't have your data ...

# Imported 0 records. Simplifying into dataframe...
# data frame with 0 columns and 0 rows
2

Try to add:

js <- '[{"$unwind":"$cdr"}, {"$lookup":{"from": "inventory", localField:}]'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.