无法访问Json输出

时间:2017-03-20 15:12:01

标签: javascript php json

PHP代码:

$contents = '';
$dataarray = file('/location/'.$_GET['playlist'].''); //Push file data into array
$finallist = '';

//Grab Track Info

foreach ($dataarray as $line_num => $line) //Loop Through Data
{
    $line = str_replace("\n", "", $line); //Replace new line on string

    $contents = functionCommand($con, 'uinfo '.$line); //Returns Json for that single track
    if (stripos($contents, '"error":"invalid argument (should be a Spotify URI)"') == FALSE && stripos($contents, '"error": "invalid command"') == FALSE) //If we found tracks
    {
        $finallist .= $contents;
    }
    else
    {
        echo "Fail";
    }
}
$array = explode("\n", $finallist);
array_pop($array);
echo json_encode($array);

JAVASCRIPT:

我正在尝试访问我的json响应。 我使用内置的php函数将我的数组转换为带有json_encode($array)的json输出。

我的返回json输出:

["{\"type\":\"track\",\"artist\":\"Jax Jones, Raye\",\"title\":\"You Don't Know Me\",\"album\":\"You Don't Know Me\",\"duration\":214000,\"offset\":0,\"available\":true,\"popularity\":88}","{\"type\":\"track\",\"artist\":\"MK, Becky Hill\",\"title\":\"Piece of Me\",\"album\":\"Piece of Me\",\"duration\":189000,\"offset\":0,\"available\":true,\"popularity\":65}","{\"type\":\"track\",\"artist\":\"Wankelmut, Emma Louise\",\"title\":\"My Head Is A Jungle - MK Remix \/ Radio Edit\",\"album\":\"My Head Is A Jungle (MK Remix \/ Radio Edit)\",\"duration\":205000,\"offset\":0,\"available\":true,\"popularity\":62}"]

然后我使用JSON.parse()来解析数据。返回的输出是:

Array [ "{"type":"track","artist":"Jax Jones…", "{"type":"track","artist":"MK, Becky…", "{"type":"track","artist":"Wankelmut…" ]

我试图通过以下几种方式访问​​:

responsedata = JSON.parse(data); //Parse the data
console.log(responsedata.artist[0]); //undefined
console.log(responsedata[0].artist); //undefined

编辑(完整代码)

$.ajax({
    url : '/db/',
    cache: false,
    data: {cmd: 'viewspotplaylist',playlist: 'Williams Mix'}
}).done(function(data) 
{
    //console.log(data);
    //Something here to make code work.
    //data returns that weird array
});

如果我console.log(data)我得到了回复:

["{\"type\":\"track\",\"artist\":\"Jax Jones, Raye\",\"title\":\"You Don't Know Me\",\"album\":\"You Don't Know Me\",\"duration\":214000,\"offset\":0,\"available\":true,\"popularity\":88}","{\"type\":\"track\",\"artist\":\"MK, Becky Hill\",\"title\":\"Piece of Me\",\"album\":\"Piece of Me\",\"duration\":189000,\"offset\":0,\"available\":true,\"popularity\":65}","{\"type\":\"track\",\"artist\":\"Wankelmut, Emma Louise\",\"title\":\"My Head Is A Jungle - MK Remix \/ Radio Edit\",\"album\":\"My Head Is A Jungle (MK Remix \/ Radio Edit)\",\"duration\":205000,\"offset\":0,\"available\":true,\"popularity\":62}"]

4 个答案:

答案 0 :(得分:1)

您的输入数据是一个字符串数组,您需要构建完整的字符串。

此代码有助于:

responsedata = JSON.parse("[" + data.join(",") + "]");

答案 1 :(得分:1)

你的JSON:

 Array [ "{"type":"track","artist":"Jax Jones…", 
"{"type":"track","artist":"MK, Becky…", 
"{"type":"track","artist":"Wankelmut…" 

似乎格式错误。不应该有"{"type":

的引号

您必须以不同方式解析JSON。 在你的控制台中声明:

var data = ["{\"type\":\"track\",\"artist\":\"Jax Jones, Raye\",\"title\":\"You Don't Know Me\",\"album\":\"You Don't Know Me\",\"duration\":214000,\"offset\":0,\"available\":true,\"popularity\":88}","{\"type\":\"track\",\"artist\":\"MK, Becky Hill\",\"title\":\"Piece of Me\",\"album\":\"Piece of Me\",\"duration\":189000,\"offset\":0,\"available\":true,\"popularity\":65}","{\"type\":\"track\",\"artist\":\"Wankelmut, Emma Louise\",\"title\":\"My Head Is A Jungle - MK Remix \/ Radio Edit\",\"album\":\"My Head Is A Jungle (MK Remix \/ Radio Edit)\",\"duration\":205000,\"offset\":0,\"available\":true,\"popularity\":62}"]

然后解析你的数据:

var responsedata = JSON.parse("[" + data.join(",") + "]");

然后你可以使用responsedata [i],其中i是一个索引值来访问每个数据元素。

E.g。

console.log(responsedata[0].artist);

修改

 $.ajax({
        url : '/db/',
        cache: false,
        data: {cmd: 'viewspotplaylist',playlist: 'Williams Mix'}
    }).done(function(data) 
        {
            //console.log(data);

        // To convert data to an array, you can do:

        var dataArray = Array.prototype.slice.call(data);
        var responsedata = JSON.parse("[" + dataArray.join(",") + "]");
        console.log(responsedata[0].artist); // This does not work?
    });

答案 2 :(得分:1)

检查此脚本



var data = ["{\"type\":\"track\",\"artist\":\"Jax Jones, Raye\",\"title\":\"You Dont Know Me\",\"album\":\"You Dont Know Me\",\"duration\":214000,\"offset\":0,\"available\":true,\"popularity\":88}", "{\"type\":\"track\",\"artist\":\"MK, Becky Hill\",\"title\":\"Piece of Me\",\"album\":\"Piece of Me\",\"duration\":189000,\"offset\":0,\"available\":true,\"popularity\":65}", "{\"type\":\"track\",\"artist\":\"Wankelmut, Emma Louise\",\"title\":\"My Head Is A Jungle - MK Remix \/ Radio Edit\",\"album\":\"My Head Is A Jungle (MK Remix \/ Radio Edit)\",\"duration\":205000,\"offset\":0,\"available\":true,\"popularity\":62}"];
    if (typeof data != 'object')
        data = JSON.parse(data);
    var jsonArray = [];
    $.each(data, function (index, item) {
        jsonArray.push(JSON.parse(item));
    });
    console.log(jsonArray[0].artist);

	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.2/jquery.min.js"></script>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

首先,我要感谢大家的帮助和努力让我前进!

我决定回到PHP方面并重新编码它只回显变量$ finallist而不是将它放入数组然后json编码!然后在Javascript方面,我从数据中创建了一个数组,然后使用上面提供的一些信息让我走了。

最终产品:

$.ajax({
    url : '/db/',
    cache: false,
    data: {cmd: 'viewspotplaylist',playlist: 'Williams Mix'}
}).done(function(data) 
{
    var dataarray = [];
    dataarray = data.split("\n");
    dataarray.pop();
    console.log(dataarray);
    var responsedata = JSON.parse("[" + dataarray.join(",") + "]"); //Parse the data
    console.log(responsedata[0].artist); //Displays
});

谢谢!