laur
laur

Reputation: 500

How to use JSON.parse or eval () to display an array?

I have this code to save values ​​in json string in a session variable, which I call from ajax

I have the following code:

(function ($) { 

    Drupal.behaviors.MyfunctionTheme = {
        attach: function(context, settings) {

     $('.add-music').click(function () {
         var songNew = JSON.stringify({
             title: $(this).attr('data-title'),
             artist: $(this).attr('data-artist'),
             mp3: $(this).attr('href')
         });
         var songIE = {json:songNew};
         $.ajax({
             type: 'POST',
             data: songIE,
             datatype: 'json',
             async: true,
             cache: false                
         })
         .done(
              //this is the callback function, which will run when your POST request returns
            function(postData){
                //Make sure to test validity of the postData here before issuing the GET request
                var session;
                $.ajaxSetup({cache: false})
                $.get('/getsession.php', function (getData) {
                      session = getData;
                        alert(session);
                });

              }
         );

     });

}}

})( jQuery );

I have the following code that works fine, I just printed the following alert:

["{\"title\":\"El Derecho de las Mujeres a La Comunicaci\u00f3n\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/Cun%CC%83aDerechoMujeresaLaComunicacion.mp3\"}","{\"title\":\"Objetivos del encuentro internacional de Derechos Humanos en el Bajo Aguan.\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/objetivos_del_encuentro_dh.mp3\"}"]

and I need to have something like this:

[
  {
    title:"Cro Magnon Man",
    artist:"The Stark Palace",
    mp3:"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"
  },
  {
    title:"Hidden",
    artist:"Miaow",
    mp3:"http://www.jplayer.org/audio/mp3/Miaow-02-Hidden.mp3"
  }
]

How I can work this data with jquery?

thank's

Upvotes: 0

Views: 2227

Answers (4)

MFARID
MFARID

Reputation: 720

var display = JSON.stringify(jsonObject, undefined, 2); // indentation level = 2

Upvotes: 0

jropella
jropella

Reputation: 589

Your sample input is actually an array of strings. You need to parse each element within the array as an object. Using jQuery:

var input = ["{\"title\":\"El Derecho de las Mujeres a La Comunicaci\u00f3n\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/Cun%CC%83aDerechoMujeresaLaComunicacion.mp3\"}","{\"title\":\"Objetivos del encuentro internacional de Derechos Humanos en el Bajo Aguan.\",\"artist\":\"\",\"mp3\":\"http:\/\/red.comppa.com\/sites\/default\/files\/audios\/objetivos_del_encuentro_dh.mp3\"}"];

var resultArray = new Array();

for(var i = 0; i < input.length; i++){
    var parsedElement = $.parseJSON(input[i]);
    resultArray.push(parsedElement);
}

Upvotes: 0

Joshua
Joshua

Reputation: 3603

This is what JSON.parse() was designed to do. Eval() is not the approach to use here. To clarify, JSON.parse() takes valid, appropriately escaped JSON strings and converts them into usable objects within Javascript. eval(), on the other hand, is designed to take strings and attempt to EXECUTE them as Javascript functions, objects, variables, etc.

Upvotes: 0

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276446

Assuming the data is stored in a variable called yourObject you can do:

var result = JSON.parse("["+yourObject[0]+"]");

Here is a working bin

Upvotes: 2

Related Questions