javascript - 在 NodeJS 中解析类似 JSON 的数据

标签 javascript json node.js

我通过 NodeJS 从 API 调用中获得了类似于 JSON 的数据。

我收到的回复是:

{ abc: 10,
  qwe: 5 }

如果上面如下图所示:

{ "abc": 10,
  "qwe": 5 }

我本来可以使用 JSON.parse 函数,但前者不能与 JSON.parse 一起使用。

有什么方法可以从该响应中获取 qwe 的值吗?

最佳答案

选项 1:它已经是一个对象。

您显示的项目已经是一个对象。不需要解析。 JSON.parse() 旨在遍历字符串并将其转换为对象。只需处理对象本身。

示例:

const object = {abc:10, qwe:5};

console.log(object.abc);       // > 10
console.log(object["qwe"]);    // > 5

选项 2:它是一个非 JSON 字符串。

在这种情况下,也许您可​​以预测模式并手动转换为稍后可以解析的 JSON 格式?

类似于:

const nonJson = "{abc: 10, qwe: 5 }";
let jsoned = nonJson.replace(/(:\s+)/g, "\":\"");
jsoned = jsoned.replace(/(,\s+)/g, "\",\"");
jsoned = jsoned.replace(/({\s*)/, "{\"");
jsoned = jsoned.replace(/(\s+})/, "\"}");

const object = JSON.parse(jsoned);

关于javascript - 在 NodeJS 中解析类似 JSON 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48601426/

相关文章:

javascript - ERR_SSL_PROTOCOL_ERROR - Socket.io 和 Node.js

javascript - 如何修复nodejs Express服务器中的 "MulterError: Unexpected field"?

javascript - 降级 react-native 的适当机制

javascript - jQuery 是否可以连接两个选择器变量?

javascript - 在父DIV下按类查找DIV

javascript - 使用 API V3 的主要谷歌地图故障

jquery - SweetAlert 下拉列表动态添加列表中的项目

json - 在 bash 中将无效的 json 转换为有效的

php - 在php中必须从jquery [object Object]获取数据

node.js - Google App Engine 如何实现分析(堆栈跟踪)?