简体   繁体   English

用JavaScript打印JSON词典

[英]Printing JSON Dictionary in JavaScript

I am getting the data from an API using JavaScript. 我正在使用JavaScript从API获取数据。

The statement console.log(json[0]) gives the result: 语句console.log(json[0])给出结果:

{"id":"1","username":"ghost","points":"5","kills":"18","xp":"10","diamonds":"0","level":"1","missionscomplete":"1"} 

Now I am trying to print the individual elements of this dictionary. 现在,我尝试打印该词典的各个元素。 How do I do this ? 我该怎么做呢 ? My code is below: 我的代码如下:

function loadLeaderboard(){
    $.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
        var json = $.parseJSON(data);
        console.log(json[0]);
        $.each(json[i], function(key, data) {
            console.log(key + ' -> ' + data);
        });
    });
}

EDIT : The value of data as returned by the API is 编辑 :API返回的数据值是

["{\"id\":\"1\",\"username\":\"ghost\",\"points\":\"5\",\"kills\":\"18\",\"xp\":\"10\",\"diamonds\":\"0\",\"level\":\"1\",\"missionscomplete\":\"1\"}","{\"id\":\"2\",\"username\":\"seconduser\",\"points\":\"0\",\"kills\":\"3\",\"xp\":\"0\",\"diamonds\":\"0\",\"level\":\"0\",\"missionscomplete\":\"0\"}","{\"id\":\"3\",\"username\":\"goat\",\"points\":\"12\",\"kills\":\"13\",\"xp\":\"14\",\"diamonds\":\"10\",\"level\":\"10\",\"missionscomplete\":\"4\"}"] 

The value in json after the operation var json = $.parseJSON(data); 操作var json = $.parseJSON(data);之后的json中的值var json = $.parseJSON(data); is

["{"id":"1","username":"ghost","points":"5","kills":…diamonds":"0","level":"1","missionscomplete":"1"}", "{"id":"2","username":"seconduser","points":"0","ki…diamonds":"0","level":"0","missionscomplete":"0"}", "{"id":"3","username":"goat","points":"12","kills":…amonds":"10","level":"10","missionscomplete":"4"}"]

json[0] is an object, so you want to loop over the keys: json[0]是一个对象,因此您想遍历键:

var o = json[0];
for (var key in o) {
    if (o.hasOwnProperty(key)) {
        console.log(key, o[key]);
    }
}

Working fiddle: http://jsfiddle.net/UTyDa/ 工作提琴: http : //jsfiddle.net/UTyDa/

Update 更新资料

Your JSON data is a mess. 您的JSON数据一团糟。 It's not in the format you want. 它不是您想要的格式。 It should be an array of objects, but instead it is an array of strings , where each of those strings is the JSON representation of one of your user objects. 它应该是一个对象数组,但是应该是一个字符串数组,其中每个字符串都是您的一个用户对象的JSON表示形式。

You could decode this in your JavaScript code, but you shouldn't have to. 可以在JavaScript代码中对此进行解码,但不必这样做。 The JSON API should be fixed to generate a reasonable JSON object. JSON API应该固定为生成合理的JSON对象。

I don't know what language your server code is in, but it must be doing something like this pseudocode: 我不知道您的服务器代码使用的是哪种语言,但是它必须正在执行类似以下伪代码的操作:

array = []
for each userObject in leaderBoard:
    userJson = toJSON( userObject )
    array.push( userJson )
jsonOutput = toJSON( array )

Instead, the code should look more like this: 相反,代码应看起来像这样:

array = []
for each userObject in leaderBoard:
    array.push( userObject )
jsonOutput = toJSON( array )

In other words, the way to generate the JSON you want in most languages is to create an object or array with the structure you need, and then call the language's toJSON function (or whatever function you use) on that object or array. 换句话说,在大多数语言中生成所需JSON的方法是创建具有所需结构的对象或数组,然后在该对象或数组上调用该语言的toJSON函数(或使用的任何函数)。 Let it generate all of the JSON in one fell swoop. 让它一次生成所有JSON。 Don't generate JSON for each individual element of your array and then generate JSON again for the entire array as a whole. 不要为数组的每个元素生成JSON,然后再为整个数组再次生成JSON。 That gives you an array of strings where you want an array of objects. 这样就可以在需要数组对象的地方提供一个字符串数组。

Original answer 原始答案

What you're asking for is not what you really want to do. 您所要的不是您真正想要做的。

Your JSON response returns an array of user objects, correct? 您的JSON响应返回一个用户对象数组,对吗? That's why json[0] is a single object. 这就是json[0]是单个对象的原因。

You probably want to loop over that array , but you don't loop over the individual objects in the array. 您可能想遍历该数组 ,但不要遍历该数组中的各个对象 You simply reference their properties by name. 您只需按名称引用它们的属性。

Also, instead of using $.get() and $.parseJSON() , you can use $.getJSON() which parses it for you. 另外,可以使用$.getJSON()代替它来使用$.get()$.parseJSON()$.getJSON()它。

And one other tip: don't put the hostname and port in your URL. 还有一个提示:不要在您的URL中输入主机名和端口。 Use a relative URL instead, and then you can use the same URL in both development and production. 请使用相对URL,然后在开发和生产中都可以使用相同的URL。

So for test purposes, let's say you want to log the id , username , and points for each user in your leaderboard JSON array. 因此,出于测试目的,假设您要记录排行榜JSON数组中每个用户的idusernamepoints You could do it like this: 您可以这样做:

function loadLeaderboard() {
    var url = '/l4/public/api/v1/getLeaderboard';
    $.getJSON( url, function( leaders ) {
        // leaders is an array of user objects, so loop over it
        $.each( leaders, function( i, user ) {
            // get the properties directly for the current user
            console.log( user.id, user.username, user.points );
        });
    });
}

您可以只使用JSON-的stringify方法

console.log(JSON.stringify(json[0]));

jQuery.each() is probably the easiest way, check this out: http://api.jquery.com/jQuery.each/ jQuery.each()可能是最简单的方法,请查看: http : //api.jquery.com/jQuery.each/

eg 例如

$.each(json[0], function(key, data) {
    console.log(key + ' -> ' + data);
});

EDIT: 编辑:

What's the result of the following? 以下结果是什么?

function loadLeaderboard(){
    $.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
        var json = $.parseJSON(data);
        console.log(json[0]);
        for(var i = 0; i < json.length; i++) {
            $.each(json[i], function(key, data) {
                console.log(key + ' -> ' + data);
            });
        }
    });
}

EDIT 2: 'data' returned as array. 编辑2: '数据'返回为数组。

function loadLeaderboard(){
    $.get("http://localhost:8888/l4/public/api/v1/getLeaderboard", function(data){
    for(var i = 0; i < data.length; i++) {
            var json = $.parseJSON(data[i]);
            console.log('Data for index: ' + i);
            $.each(json, function(key, val) {
                    console.log(key + ' -> ' + val);
            });
    }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM