简体   繁体   中英

How to cast/parse API response from Node.JS

I have a line of code in Node.js that call an external API:

public.getInfo(console.log, config.data1);

and retrieve some data:

null { abc:
   {field1: 0.234252,
   {field2: 0.234252,
   {field3: 0.234252,
   {field4: 1,
   {field5: 0.234252 },
{ xzy:
   {field1: 0.234252,
   {field2: 0.234252,
   {field3: 0.234252,
   {field4: 0.234252,
   {field5: 0.234252 }}

I can see the result in the console. I have two questions:

  1. public.getInfo(console.log, config.data1); has console.log as "callback" function. What if I do not want to print this data, but just use it in other functions in my code?

  2. How do I "read" the API response? How do I use the JSON structure of the response? For example: abc -> fiels4 => 1

I'm not sure due to lack of code, but I think config is a variable you have set somewhere and you receive data from config.data1 .

Use config.data1[0].field4 to read the object property of abc -> field4 => 1

Or read the other ways to read properties https://www.w3schools.com/js/js_properties.asp

I have actually founded a solution...

public.getInfo(function(err,data){  
console.log(data[config.data1].field4)
return true
},
config.data1);

This gives me the correct value of the returned API call... (in the console)...

But how to use the value outside the public.getInfo function? do I need to create a variable? confused

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM