javascript - MongoDB 有问题的 JSON prop/field

标签 javascript json node.js mongodb express

我使用以下代码收到了来自“请求”的响应:

collection.distinct('id', (err, docs) => {
    docs.forEach(id => {
        let url = 'url.com/id=' + id
        request(url, (error, response, body) => {
            var resp = JSON.parse(response.body.replace('._', '_'));
            collection2.insert(resp);
        });
    });
});

response.body 返回一个字符串化的 JSON,其中一些字段和属性包含句点,例如:

MISC._EXTERIOR_FEATURES": {
    "id": 29,
    "name": "MISC._EXTERIOR_FEATURES",
    "attributes": {
      "ROOF_RACK": {
      "id": 0,
      "name": "ROOF_RACK",
      "value": "roof rack"
    }
}

代码解释:对于集合中的每个不同的 id,请求 id 的 url。然后,使用response.body(字符串),我使用.replace()来“清理”字符串化的JSON,然后解析它,并将其插入到collection2中。

错误:

(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 33): Error: key MISC._EXTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 34): Error: key MISC._INTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 35): Error: key MISC._EXTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 36): Error: key MISC._INTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 37): Error: key MISC._INTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 38): Error: key MISC._INTERIOR_FEATURES must not contain '.'
(node:24552) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 39): Error: key MISC._EXTERIOR_FEATURES must not contain '.'

最佳答案

不确定为什么键不能包含“.”,但您的“替换”仅替换第一次出现的情况。尝试正则表达式。

.replace(/\._/g, '_')

关于javascript - MongoDB 有问题的 JSON prop/field,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44034032/

相关文章:

php - 检查 IE 并显示另一个页面

javascript - <div> 标签未显示 Ajax 的 JSON 响应

javascript - Angular 和 Spring Rest api 通过 https 进行通信

javascript - json 到 javascript 变量 zendesk

java - 无法解析 JSON 中的古吉拉特语文本

node.js - 使用 mocha 测试二进制文件上传

javascript - 在javascript中将回调函数设置为新窗口

python - 从嵌套的 JSON 文档中提取值

node.js - NodeJS Passport session 序列化 - 将用户反序列化到 session 中?

node.js - 将 md5 哈希值添加到 mongo 集合