doushu7588 2015-03-23 04:16
浏览 83
已采纳

javascript / jquery通过名称和索引访问JSON数组

I am very much hoping you can help me with this as I've spent all too much time on this. First, my JSON formatting is unfortunately not very mutable and I have moved it to a number of different formats to support both some jquery and a php-based search. Each time I move it, the search will work and the rest of the site will break or vice-versa.

Is it possible to access a JSON array by both name and index number? Here is my JSON (stored in PHP file and being retrieved & converted successfully to valid JSON):

<?php

$contents = array(
'Song Name #1 by Artist Name #1 (maininfo)' => array(
    'contentid' => '1',
    'aname' => 'Artist Name',
    'sname' => 'Song Name',
    'main' => 'core content #1',
    'maininfo' => 'url')
),
'Song Name #2 by Artist Name #2 (maininfo)' => array(
    'contentid' => '2',
    'aname' => 'Artist Name',
    'sname' => 'Song Name',
    'main' => 'core content #2',
    'maininfo' => 'url')
);

?>

My search works when something in the array title is matched on, otherwise it returns no matches so I must leave the array title as-is.

Another part of my project uses jquery and has the following:

parse(jsonobj[0][1]['sname']) //successfully already returning 'Song Name'

The above will ONLY work when the array title is not provided (e.g. 'Song Name #1 by Artist Name #1 (maininfo)' => array( becomes simply array(.

For those curious, file is being converted to JSON using:

var jsonobj;

    $.ajax({
        url: 'getjson.php',
        dataType: "json",
        success: function (doc) {

        jsonobj = doc;

        }
  });

On the PHP side, when getjson.php is called the JSON array (above) is loaded in and converted to valid JSON using:

$final = array($final_contents);
header('Content-type: application/json');
echo json_encode($final);

Note: $final_contents is just $contents with an additional header added. See Searching JSON array for values and accessing surrounding keys/values; output as JSON for the PHP I have running specifically.

Thank you in advance.

  • 写回答

2条回答 默认 最新

  • duanlu9816 2015-03-23 04:27
    关注

    JavaScript does not support arrays with named indexes. You should encode it as a JSON object instead.

    var $contents = {
        "Song Name #1 by Artist Name #1 (maininfo)": {
            "contentid": 1,
            "aname": "Artist Name",
            "sname": "Song Name",
            "main": "core content #1",
            "maininfo": "url"
        },{
        "Song Name #2 by Artist Name #2 (maininfo)": {
            "contentid": 2,
            "aname": "Artist Name",
            "sname": "Song Name",
            "main": "core content #2",
            "maininfo": "url"
        }
    };
    

    Although it would probably be better to arrange it this way (here's a fiddle to demonstrate:

    var songs = [
        {
            "contentid": 1,
            "artist": "Artist Name",
            "title": "Song Title 1",
            "main": "core content #1",
            "maininfo": "url"
        },
        {
            "contentid": 2,
            "artist": "Artist Name",
            "title": "Song Title 2",
            "main": "core content #2",
            "maininfo": "url"   
        }
    ];
    

    Then you can search through your songs list by id, or iterate through to filter on specific field values. For instance to find all songs whose titles start with "Song Title":

    var findAllSongs = function(prop, value){
        var result = new Array();
        for (var i = 0; i < songs.length; i++) {
            var song = songs[i];
            if (song[prop] && (song[prop] === value || song[prop].search(value) >= 0)){
                result.push(song);
            }
        }
        return result;
    };
    
    var song = findAllSongs("title","Song Title 2")[0];
    alert(song.contentid);
    // Outputs "2"
    

    The php equivalent of my json above is:

    $songs = array(
        array(
            "contentid" => 1,
            "artist" => "Artist Name",
            "title" => "Song Title 1",
            "main" => "core content #1",
            "maininfo" => "url",
        ),
        array(
            "contentid" => 2,
            "artist" => "Artist Name",
            "title" => "Song Title 2",
            "main" => "core content #2",
            "maininfo" => "url",    
        )
    );
    

    If you're using PHP 5.4 or higher, you can use the short syntax:

    $songs = [
        [
            "contentid" => 1,
            "artist" => "Artist Name",
            "title" => "Song Title 1",
            "main" => "core content #1",
            "maininfo" => "url",
        ],[
            "contentid" => 2,
            "artist" => "Artist Name",
            "title" => "Song Title 2",
            "main" => "core content #2",
            "maininfo" => "url",    
        ]
    ];
    

    Then you can turn it into JSON by using your current method:

    json_encode($songs);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制