0

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?

8
  • 1
    Do you need to parse the data, or is it actually already in json format? What happens when you try to log data.qwe from your request for example? It may help us if you show a little more code surrounding the result that gives you the format in question. Commented Feb 3, 2018 at 20:00
  • It is in the former format (one without the quotes). So, I cannot parse it with JSON.parse neither data.qwe Commented Feb 3, 2018 at 20:02
  • 1
    How is source generated? Should fix it there Commented Feb 3, 2018 at 20:04
  • I cannot do that, I am using some one else' api. Commented Feb 3, 2018 at 20:05
  • is the reply a string? how do you store that reply? Commented Feb 3, 2018 at 20:08

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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!

2 Comments

Should also note that it doesn't come without serious security concerns also
You're right, eval is dangerous, only to be used with a trusted source.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.