简体   繁体   English

Javascript(Ajax)解析JSON值

[英]Javascript (Ajax) Parse JSON value

total javascript noob here. 总的JavaScript新手在这里。 Just trying to get an understanding for the language. 只是想对语言有所了解。

I'm requesting a JSON request using the following code: 我正在使用以下代码请求JSON请求:

function request(){
$.ajax({
        dataType: "jsonp",
        type: 'GET',
url: "getWebsite",
        success: function(result){
            data = result;
            $('.data').text(data);
            console.log(data);
    }});

The get request returns something like this: get请求返回如下内容:

"items": [ 
 {
  "topLevelComment": {
    "authorDisplayName": "a"
    "textDisplay": "b"
 },
 {
  "topLevelComment": {
    "authorDisplayName": "c"
    "textDisplay": "d"
 }

I would like to cycle through the AuthorDisplayName and textDisplay and randomly pick one from each. 我想遍历AuthorDisplayName和textDisplay并从中随机选择一个。 The best way to do this would probably be to put them both into arrays if I had to guess. 最好的方法可能是将它们都放入数组(如果我不得不猜测的话)。 I'm not sure how to even go about this. 我不确定该如何解决。

 var json={ "items": [{ "topLevelComment": { "authorDisplayName": "a", "textDisplay": "b" } }, { "topLevelComment": { "authorDisplayName": "c", "textDisplay": "d" } }, { "topLevelComment": { "authorDisplayName": "e", "textDisplay": "f" } }, { "topLevelComment": { "authorDisplayName": "g", "textDisplay": "h" } }] }; $("input:button").on("click",function(){ selectRand = Math.floor((Math.random() * json.items.length)) var r=json.items[selectRand].topLevelComment.textDisplay; console.log(r); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="button" value="selectRand"/> 

items is already an array. items已经是一个数组。 So you do the following: 因此,您需要执行以下操作:

  1. Parse the result to json (Only if a string is returned) 将结果解析为json(仅当返回字符串时)

    items = JSON.parse(items)

  2. Get a random index 获取随机索引

    let index = Math.floor((Math.random() * items.length))

  3. Get the random data 获取随机数据

    let authorDisplayName = items[index].topLevelComment.authorDisplayName
    let textDisplay = items[index].topLevelComment.textDisplay

As far as i understood you are trying to display a random object from the items array? 据我了解,您正在尝试从items数组中显示一个随机对象?

The items variable is already an array, so you don't need to create one. items变量已经是一个数组,因此您无需创建一个数组。 To get a random element of the array you can use the following code: 要获得数组的随机元素,可以使用以下代码:

var item = result.items[Math.floor(Math.random()*items.length)];

I'm not sure where exactly the items array is located, let's say it's on the root of the result. 我不确定items数组的确切位置,可以说它位于结果的根上。 You will probably also need to run the array through the method JSON.parse() to make it a valid JavaScript object. 您可能还需要通过JSON.parse()方法运行数组,以使其成为有效的JavaScript对象。

And then to get the text and display name you can do this: 然后,要获取文本和显示名称,可以执行以下操作:

var authour = item.topLevelComment.authorDisplayName; var text = item.topLevelComment.textDisplay;


If your data is already in Object format, and you only want to get one from random pick. 如果您的数据已经是对象格式,并且您只想从随机选择中获取一个即可。 Then you don't have to loop for all the data. 然后,您不必循环所有数据。 Just randomly select one index from your total data. 只需从总数据中随机选择一个索引即可。

function request(){
    $.ajax({
        dataType: "jsonp",
        type: 'GET',
        url: "getWebsite",
        success: function(result){
            data = result;
            $('.data').text(data);
            console.log(data);

            var randomIndex = Math.floor((Math.random() * data.items.length));
            console.log("Selected data authorDisplayName: " + data.items[randomIndex].topLevelComment.authorDisplayName);
            console.log("Selected data textDisplay: " + data.items[randomIndex].topLevelComment.textDisplay);
        }
    });
}

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

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