Leveraging the api.call function to parse JSON data in a nodejs

I'm currently working on extracting data from a JSON response obtained through an API. Although I am able to stringify the response, I'm facing difficulties in parsing the JSON data and specifically retrieving the value of "display_name" into a variable.

Below is my current code snippet:

var api = require('twitch-irc-api');

api.call({
    channel: null,
    method: 'GET',
    path: '/channels/greatbritishbg/follows',
    options: {
        limit: 1,
        offset: 0
    }
}, function(err, statusCode, response) {
    if (err) {
        console.log(err);
        return;
    }
    console.log('Status code: ' + statusCode);
    console.log('Response from Twitch API:');
    console.log(JSON.stringify(response));
    console.log(JSON.parse(response);
});

Stringified Response Output:

Response from Twitch API: {"follows":[{"created_at":"2015-06-02T06:11:10Z","_links":{"self":" witch.tv/kraken/users/feddecampo/follows/channels/greatbritishbg"},"notification s":false,"user":{"_id":50947595,"name":"feddecampo","created_at":"2013-11-01T17: 22:49Z","updated_at":"2015-05-30T19:50:21Z","_links":{"self":" .tv/kraken/users/feddecampo"},"display_name":"FeddeCampo","logo":" cdn.jtvnw.net/jtv_user_pictures/feddecampo-profile_image-d4f7de23b28e0a86-300x30 0.jpeg","bio":"Playstation MVP Sony and PS fan ","type":"user"}}],"_total":2315, "_links":{"self":" irection=DESC&limit=1&offset=0","next":" eatbritishbg/follows?direction=DESC&limit=1&offset=1"}}

Answer №1

The data has already been 'organized'

When you structure the information, it becomes more readable:

{  
   "followers":[  
      {  
         "creation_date":"2015-06-02T06:11:10Z",
         "_links":{  
            "self":"https://api.twitch.tv/kraken/users/feddecampo/follows/channels/greatbritishbg"
         },
         "notifications":false,
         "user":{  
            "_id":50947595,
            "name":"feddecampo",
            "creation_date":"2013-11-01T17: 22:49Z",
            "last_updated":"2015-05-30T19:50:21Z",
            "_links":{  
               "self":"https://api.twitch.tv/kraken/users/feddecampo"
            },
            "display_name":"FeddeCampo",
            "logo":"http://static-cdn.jtvnw.net/jtv_user_pictures/feddecampo-profile_image-d4f7de23b28e0a86-300x300.jpeg",
            "bio":"Playstation MVP Sony and PS fan ",
            "account_type":"user"
         }
      }
   ],
   "_total":2315,
   "_links":{  
      "self":"https://api.twitch.tv/kraken/channels/greatbritishbg/follows?direction=DESC&limit=1&offset=0",
      "next":"https://api.twitch.tv/kraken/channels/greatbritishbg/follows?direction=DESC&limit=1&offset=1"
   }
}

You can access the values using regular javascript notation:

var displayName = data.followers[0].user.display_name

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Storing dates using Angular 2 and JSON for efficient data management

I've encountered a challenging issue with my Angular 2 application. I'm attempting to organize my API (MongoDB) in such a way that each new "post" added by the admin can be retrieved by date (not time) on the front end. Here's an example of ...

How can I call module.exports.myInstance within a function that belongs to a different file?

Is there a way to access module.exports.myInstance in a function from another file? Here is an example of the code structure: // File: a.js const func = async function () { ... module.exports.myInstance = ...; } func(); // File: b.js const module = re ...

Python Scrap Data Project

I attempted to extract data using Xpath, but unfortunately, it was unsuccessful. My aim is for the code to retrieve information from specific columns on the website "https://www.destatis.de/DE/Themen/Gesellschaft-Umwelt/Bevoelkerung/Geburten/Tabellen/leben ...

Tips for maintaining ajax headers and enabling CORS in Angular resource requests

Within my ng-resource files, I have configured the ajax header as follows: var app = angular.module('custom_resource', ['ngResource']) app.config(['$httpProvider', function($httpProvider) { //enable XMLHttpRequest, indic ...

Having trouble globally installing express-generator using nvm

My current setup involves using NVM to bypass the need for utilizing sudo when installing global packages. This method successfully handles installations of tools like Bower and Grunt, but hits a snag when attempting to install Express Generator globally u ...

Obtain an image from the public/uploads/image directory in Node.js while ensuring the image quality is represented as

I am looking to store only one original image in my folder, but retrieve it in different quality levels. For example, here is the same image at 5% quality: https://i.stack.imgur.com/TUPRy.jpg And here is the same image at 100% quality: https://i.stack. ...

JavaScript - Merging the two JSON requests into a unified object

Is there a way to merge two different JSON responses into a single object for easy data manipulation? I've explored various solutions, but none seem to align with my current code structure. Given that I'm new to this, it would be incredibly hel ...

Guide on sending an http request using Atlas Trigger in a NodeJS environment

I am working with a simple MongoDB Atlas trigger in NodeJS: exports = function(changeEvent) { // Implementing an HTTP request }; The main objective is to invoke an AWS lambda function from this trigger. Therefore, I am seeking guidance on the synta ...

Pyinstaller error: File cannot be found at 'C:\Users\my.name\Desktop\EPE 2.0\dist\main\timezonefinder\timezone_names.json'. It seems to be missing

Whenever I attempt to run my executable file generated by pyinstaller (using the latest version, Python v3.6 in an Anaconda environment), I encounter the following error: File "site-packages\timezonefinder\timezonefinder.py", line 27, in <mod ...

I've been endeavoring to compare the content IDs from two APIs using Jmeter

I am faced with a challenge where I have two APIs that contain the same content but have different URLs. My goal is to compare all the contents from both APIs using jmeter. So far, I have utilized the json extractor by setting the path as $..contentid and ...

Having issues with my npm, it's acting up

I'm encountering issues with my npm that seem to persist regardless of whether I try to install using a package.json file or simply installing a node module. Here is the error message that appears in the terminal: npm http GET https://registry.npmjs. ...

php script within a literal .tpl file

Is there a way to perform a json_encode within a literal javascript block in the context of a Smarty template? {literal} <script> function openWin() { var O = {php} echo json_encode($obj);{/php}; // syntax error ...

Invalid integer input syntax error occurred in Node.js

Currently, I am utilizing Postgres SQL along with Node.js and Express. app.get("/topic/create", function(req, res) { var sql = "SELECT id, title FROM topic"; client.query(sql, function(err, result) { console.log(result.rows); ...

Having trouble parsing JSON data from $_POST while utilizing AngularJS

While working in Angular, I encountered the following scenario: var data = {}; data['name'] = "test"; data['class'] = "testClass"; $http.post('http://testURL',data,function(data){ console.log(data); }); Upon inspecting the ...

I'm facing a challenge where Multer is preventing me from showing images in my React app

Hi there, I'm currently facing an issue where I am using multer to save files on my server and store their path in mongodb. However, I am struggling to display them on my React application. Any assistance would be greatly appreciated. Thank you in ad ...

When a recent mongoose query is passed to a pug view, all object value pairs returned are undefined except for _id

Encountered a situation where I am only able to access the _id property of the object in my pug view. Attempting to retrieve word.name results in undefined. Here is the Node.js route: const router = require("express").Router(); const authCheck = require( ...

What is the best way to send FormData from a React JS axios post request to a Node server?

I am facing an issue where the form data is not reaching the node server even though it shows in the network payload at the time of request. Below are the snippets from different files involved in the process. let formData = new FormData(); // fo ...

Encountered a syscall spawn git error while running npm install command

I recently attempted to execute npm install and encountered the following problems: Even after attempting to clear cache forcibly, installing git, and updating node, none of these solutions proved effective. Above is the specific error message I received ...

Convert a JSON object containing strings, integers, and arrays into a map

When working with JSON strings, I prefer to use the Decode() function for unmarshalling: var data Data decoder := json.NewDecoder(input) err = decoder.Decode(&data) The structure of my data is defined as: type Data map[string]interface{} An example ...

issues encountered when attempting to generate logs in aws S3 bucket with 'winston' and 's3-streamlogger' modules

const winston = require('winston'); var S3StreamLogger = require('s3-streamlogger').S3StreamLogger; var s3_stream = new S3StreamLogger({ bucket: "bucket_name", access_key_id: "access_key_id", secret_access_key: "secret_acce ...