0

I am trying to get some JSON data from the API provided by the vendor, but i am getting error i try google it, in many comments people say to use JSON.Stringify but in my case JSON.Stringify didnt help me it returns an empty array like {}

repose from the api are as follow

[{ SYMBOL: 'FOREX',
CODE: 'REG',
LST: '219.50',
LTP: '12:52:35'}]

but my desire response is

[{ "SYMBOL" : "FOREX",
"CODE": "REG",
"LTP": '219.50',
"LST": '12:52:35'}]
Akshay Gulhane
  • 121
  • 1
  • 7
hxnAbbas
  • 43
  • 5

3 Answers3

0

Your response is on text, To convert text to JSON string,

let text = `[{ SYMBOL: 'FOREX',
CODE: 'REG',
LST: '219.50',
LTP: '12:52:35'}]`

let jsonStr = JSON.stringify(eval("(" + text + ")")); // Convert Object String to JSON
console.log(jsonStr);

Note : Make sure that your vendor is trusted source, Because eval opens up your code for injection attacks, If your are worry about this, Please contact your vendor to provide JSON response.

Reference : Convert object string to JSON

Şivā SankĂr
  • 1,966
  • 1
  • 18
  • 34
  • Eval is Evil. Do you really suggest evaluating the response from an API ? This is as bad as it can be. – Seblor Mar 12 '19 at 09:51
  • Hope that the string from trusted source. – Şivā SankĂr Mar 12 '19 at 09:52
  • The source must be trusted, as well as the network. This is not acceptable for any web app. Evaluating from an external source is the worst possible scenario. – Seblor Mar 12 '19 at 09:54
  • Answer updated to give warning the use of `eval()`. Now depends on the requirement/API source they will decide to go with `eval()` or not – Şivā SankĂr Mar 12 '19 at 10:01
0

If the JSON result provided by the vendor's API is indeed this :

[{ SYMBOL: 'FOREX',
CODE: 'REG',
LST: '219.50',
LTP: '12:52:35'}]

I have to inform you that this is invalid JSON. In JSON, the properties should be strings between double-quotes, otherwise it cannot be parsed.

Your desired response is the correct form. There is likely an error in the way the vendor is forming the output.

tl;dr : Your vendor's API is giving you a JavaScript Object, not JSON.

Seblor
  • 6,947
  • 1
  • 25
  • 46
0

Ok so what i did is use STRINGFY as a middleware and that solve my problem thanks for your help guys really appreciatable.

hxnAbbas
  • 43
  • 5