Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON key has '#' Special character

Currently I need the URL for an image and I am getting it through the JSON file. I am not sure to acquire the key that has the URL due to the key having a # at the start. Here is the JSON:

{  
 "#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png",
 "size":"small"
},
{  
 "#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png",
 "size":"medium"
}
like image 834
jhigg15 Avatar asked Oct 19 '25 11:10

jhigg15


1 Answers

Same as with every other time you encounter some JSON string!

The # is an invalid character in a property name, work around is the bracket notation: «object»[property] --> «array»[index]['#text'].

We can use forEach to extract the results.

var string = '[{"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"small"},{"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"medium"}]';

var parsed = JSON.parse(string);

//parsed is an array, we can loop over it
parsed.forEach(function(obj) {
      console.log(obj['#text']);
});

Even prettier would be if you can select from the array based on size:

var string = '[{"#text":"https://lastfm-img2.akamaized.net/i/u/34s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"small"},{"#text":"https://lastfm-img2.akamaized.net/i/u/64s/3ed37777196a6f2c29c02a1a58a93e4d.png","size":"medium"}]';

function getImageUrlBySize(size, json) {
  var parsed = JSON.parse(json);
  return parsed.find(function(element) { //modern browsers only (no IE)
      return element['size'] == size;
  })['#text']; //add text here since find returns the full item
}

console.log(getImageUrlBySize('small', string));
like image 61
Mouser Avatar answered Oct 21 '25 03:10

Mouser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!