I am getting a return from an API call through NodeJS as data similar to JSON.
I am getting the reply as:
{ abc: 10,
qwe: 5 }
If the above was as shown below:
{ "abc": 10,
"qwe": 5 }
I could have used JSON.parse function, but the former can't be used with JSON.parse.
Is there any way I can get the value of qwe
from that response?
Option 1: It's already an object.
The item you're showing is already an object. It doesn't need parsing through. JSON.parse() is meant to go through a string and turn it into an object. just work with the object itself.
Example:
const object = {abc:10, qwe:5};
console.log(object.abc); // > 10
console.log(object["qwe"]); // > 5
Option 2: It is a non-JSON string.
In this case maybe you can predict the pattern and manually turn into a JSON format that you can parse later?
something like:
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);
There is a way to do this, it's a bit ugly though, you can do:
var unquotedJson = '{ abc: 10, qwe: 5 }';
var object = eval('('+ unquotedJson +')');
NB: eval is only to be used with a trusted source, since it will execute JavaScript code.
I should also mention that unquoted JSON is not really JSON!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.