Search code examples
bixby

in Bixby javascript function how to manipulate JSON after receving from server


There is some very basic thing I don't understand about how Javascript functions work that is blocking me. In this script I am retrieving JSON from an api server. I need to modify the JSON slightly so it conforms to the data type model in Bixby.



var http = require('http');
var console = require('console')

const baseURL = 'https://www.altbrains.com/api/news/impeachmentsage';

exports.function = function getNews () {
  let options = {
    format: 'json',
    headers: {
      'accept': 'application/json'
    },
    cacheTime: 0
  };

  var response = http.getUrl(baseURL, options);

  news = response

  image_url = news.image
  console.log("image url", image_url)

    var modify;

    modify = {
        url: image_url 
      }

    console.log('modify', modify)
    news.image = modify

  console.log ('news image', news.image)
  return response;

}

the value of response is correctly reported as:

[{"image":"https://www.altbrains.com/images/48936529373_71ff9e0e13_o.jpg","tags":"news","text":"Trump's ambassador to the EU testified on Nov. 20 that 'Yes, there was a quid pro quo.'","title":"QPQ = YES"},{"image":"https://www.altbrains.com/images/48936529373_71ff9e0e13_o.jpg","tags":["news","schedule"],"text":"The next impeachment hearings by the House Permanent Select Committee on Intelligence will be held on Dec. 3.  Enjoy a peaceful Thanksgiving!","title":"What's Next"}]

The log reports that news.image is undefined, which prevents me from modifying it into the format required by Bixby, which has an "{url:" slot. Why?


Solution

  • I got this working:

    var http = require('http');
    var console = require('console')
    
    
    const baseURL = 'https://www.altbrains.com/api/news/impeachmentsage';
    
    exports.function = function getNews () {
      let options = {
        format: 'json',
        headers: {
          'accept': 'application/json'
        },
        cacheTime: 0
      };
    
      response = http.getUrl(baseURL, options);
    
      news = response
     // news = response[0]
      console.log('news', news)
      news.forEach(function(item, index, array) {
    
      image_url = news[index].image
      console.log('news story', news[index])
      console.log('news image_url', news[index].image)
    
       modified_url = {
         url: image_url 
          }
    
       news[index].image = modified_url
    
    });
    
      return news;
    }