简体   繁体   English

为什么MongoDB会产生无效的JSON? 不引用ObjectId,中断jq解析器

[英]Why does MongoDB produce invalid JSON? The ObjectId is not quoted, breaks jq parser

I've searched the forum and seen many folks with a similar problem, but not this exact one. 我在论坛上进行了搜索,看到许多人遇到类似的问题,但不是这个问题。

I think my question is the simplest form, and there must be something I'm missing because no one is asking it. 我认为我的问题是最简单的形式,肯定有我缺少的东西,因为没人问。

I have a shell script that calls a MongoDB script and gets the results in a file. 我有一个外壳程序脚本,该脚本调用MongoDB脚本并在文件中获取结果。 I then want to parse that file with jq. 然后,我想用jq解析该文件。

jq is breaking because the output from the query is not valid JSON. jq中断,因为查询的输出无效的JSON。 The offender is the ObjectId. 犯罪者是ObjectId。 I'm at a total loss as to how something that's "ALL JSON ALL THE TIME" produces invalid JSON. 关于“ ALL JSON ALL THE TIME”如何产生无效的JSON,我一无所知。

I'm pretty sure there's something fundamental that I'm missing. 我很确定我缺少一些基本知识。

I have a file called MyMongoScript.js. 我有一个名为MyMongoScript.js的文件。 Its contents look like this: 其内容如下所示:

db.WorkflowJobs.find().sort({"STATUS":1}).forEach(printjson)

I call MyMongScript.js with the following command: 我使用以下命令调用MyMongScript.js:

mongo -u $MONGO_U -p $MONGO_P $MONGO_DB -quiet --eval "var DATE_TO_RUN=\"$DATE_TO_RUN\"" MyMongoScript.js  

Here's the results to STDOUT: 这是STDOUT的结果:

{
"_id" : ObjectId("52816fd50bc9efc3e6d8e33f"),
"WORK_TYPE" : "HIVE",
"Script_Name" : "upload_metrics_LANDING_to_HIST.sql",
"Stop_On_Fail" : true,
"STATUS" : "READY",
"START_TS" : "NULL",
"END_TS" : "NULL",
"DURATION" : "NULL",
"INS_TS" : "Mon Nov 11 2013 16:01:25 GMT-0800 (PST)"
}

Here's what jsonlint.com says about it: 这是jsonlint.com关于它的内容:

Parse error on line 2:
{    "_id": ObjectId("52816fd50b
------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

Any help much appreciated. 任何帮助,不胜感激。

Try this for your MyMongoScript.js: 为您的MyMongoScript.js尝试以下操作:

db.WorkflowJobs.find().sort({"STATUS":1}).forEach(function(myDoc){myDoc._id=myDoc._id.valueOf();print(tojson(myDoc))});

The key is valueOf() which will set your ObjectId to a String. 关键是valueOf() ,它将您的ObjectId设置为String。

EDITED Left out a paren. 编辑遗漏了一个家长。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM