ERROR while accessing JSON keys with special character

Asked

Viewed 126 times

0

Good evening, Folks!

I am writing a Nodejs that accesses a URL that contains a JSON in that JSON the keys contains special character "-" that is causing error in my application which would be the correct way to access them?

Example Error:

var playing = ('#Playnow: ' + parsedRadio.data.Current-music.Song);
Referenceerror: music is not defined

Example JSON:

data: {
    current-music: {
        singer: "NOME_BANDA",
        song: "NOME_MÚSICA"
    }
}

Example Code:

const request = require('request');

request('http://myplayer.myradio.com.br/tocando.php', function (error, response, body) {
  console.log('error:', error);
  console.log('statusCode:', response && response.statusCode);
  var parsedRadio = JSON.parse(body);
  var tocando = ('#TocandoAgora: ' + parsedRadio.data.current-music.song);
  console.log(tocando);
});

I have tried the following ways and failed.

parsedRadio.data.[current-music].song
parsedRadio.data.['current-music'].song
parsedRadio.data.'current-music'.song
parsedRadio.data.currentmusic.song
parsedRadio.data.{current-music}.song

Forgive me if it’s a basic mistake, I’m still learning Nodejs. I thank you all.

1 answer

0


I believe this solves, I used Object.values() to take the values of the object. If the object is that way:

data: {
    current-music: {
        singer: "NOME_BANDA",
        song: "NOME_MÚSICA"
    }
}

const dados = Object.values(data); //retorno sera singer e song, dentro de uma lista
console.log(dados[0])//{ singer: 'NOME_BANDA', song: 'NOME_MÚSICA' } 

I believe that you do not need to convert to json object, use it the way they see it in body. Only use Object.values. I put it this way, but if there is a sub-object inside the body then yes Voce should put something like body.myobject within the Object.values.

const request = require('request');

request('http://myplayer.myradio.com.br/tocando.php', function (error, response, body) {
console.log('error:', error);
console.log('statusCode:', response && response.statusCode);
var dados = JSON.parse(body)
var parsedRadio = Object.values(dados.data)
var tocando = ('#TocandoAgora: ' + parsedRadio[0].song);
console.log(tocando);
});

Reference

  • Good evening, @Andersonmendes! Thank you for answering! but I got the following error following your solution var parsedRadio = Object.values(body.data)
 ^
TypeError: Cannot convert undefined or null to object

  • Extracts the body object in the same way you were doing before and then uses Object.value to pick up the values of the object.

  • Tested here the way I left and really gave this mistake, Czech now, modified the answer.

  • It worked, thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.