ERROR accessing JSON keys with special character

0

Good evening, guys!

I'm writing a NodeJS that accesses a URL that contains a JSON in that JSON the keys contain special "-" character that is causing error in my application what would be the correct way to access them?

Example Error:

  

var playing = ('#Touching Now:' +   parsedRadio.data.current-music.song);
  ReferenceError: music is not   defined

JSON Example:

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 I did not succeed.

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

Please forgive me if this is a basic bug, I'm still learning NodeJs. Thank you all.

    
asked by anonymous 04.09.2018 / 04:24

1 answer

0

I believe this works, I used Object.values () to get the object's values. If the object looks like this:

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 think you do not need to convert to json, use it the way it comes in the body. Only use object.values. I put it this way, but if you see a sub-object inside the body then yes you should put something like body.myobject inside 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

    
04.09.2018 / 04:58