我有这个代码在会话变量中保存json字符串中的值,我从ajax调用
我有以下代码:
(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 );
我有以下代码可以正常工作,我只是打印了以下警告:
["{\"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\"}"]
我需要这样的事情:
[
{
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"
}
]
如何使用jquery处理这些数据?
感谢的
答案 0 :(得分:2)
假设数据存储在名为yourObject
的变量中,您可以执行以下操作:
var result = JSON.parse("["+yourObject[0]+"]");
答案 1 :(得分:0)
这是JSON.parse()
的目的。 Eval()
不是在这里使用的方法。为了澄清,JSON.parse()
采用有效的,适当转义的JSON字符串,并将它们转换为Javascript中的可用对象。另一方面,eval()
旨在获取字符串并尝试将它们作为Javascript函数,对象,变量等执行。
答案 2 :(得分:0)
您的示例输入实际上是一个字符串数组。您需要将数组中的每个元素解析为对象。使用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);
}
答案 3 :(得分:0)
var display = JSON.stringify(jsonObject, undefined, 2); // indentation level = 2