如何在JSON中获取随机值

时间:2013-10-25 12:14:28

标签: javascript jquery json

我在javascript变量中有json字符串。我想从JSON字符串中获取随机值并设置为HTML。

var jsonContent= {
          "featured": [
            {
              "id": "111",
              "title": "post title 111",
              "desc": "This is a test desc 111"
            },
            {
              "id": "222",
              "title": "post title 222",
              "desc": "This is a test desc 222"
            },
            {
              "id": "333",
              "title": "post title 333",
              "desc": "This is a test desc 333"
            }
    ]
};

例如,为我的html分配第一个键值,如下所示: -

   <div class="r-v-details">
    <span class="r-v-title">post title 111</span>
    <span class="r-v-description">This is a test desc 222</span>
   </div>

如何从JSON字符串中获取随机键值?我是否需要将JSON解析为数组然后才能获得随机值?或者我只能通过json实现这个目标? 你能建议我吗?

2 个答案:

答案 0 :(得分:6)

应该是:(检查控制台中的结果)

var jsonContent = {
        "featured": [
            {
                "id": "111",
                "title": "post title 111",
                "desc": "This is a test desc 111"
            },
            {
                "id": "222",
                "title": "post title 222",
                "desc": "This is a test desc 222"
            },
            {
                "id": "333",
                "title": "post title 333",
                "desc": "This is a test desc 333"
            }
        ]
    }

    var random = jsonContent.featured[Math.floor(Math.random() * jsonContent.featured.length)];
    console.log(random)

答案 1 :(得分:2)

试试这个:

var random = jsonContent["featured"][Math.floor(Math.random()*jsonContent["featured"].length)];