javascript - 如何在 JSON 中获取随机值

标签 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 来实现? 你能建议我吗?

最佳答案

应该是:(在控制台查看结果)

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)

关于javascript - 如何在 JSON 中获取随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19589598/

相关文章:

javascript - 为呈现的 MDBootstrap 元素覆盖 CSS

javascript - 如何使用 jquery 模式将表单值发布到 Controller 函数(codeigniter)?

javascript - 如何在不重新加载页面的情况下撤消“调整大小”事件上的 DayPilot.Scheduler 操作?

python - 尝试从 django 应用程序打开 json 文件时出现编码错误

javascript - 带有不区分大小写标志 'i' 和全局的正则表达式 javascript 无法工作

jquery - 如何获取距日期选择器中所选日期 15 天以上的日期?

javascript - 单击时,将元素克隆到变量并将其附加到另一个元素

javascript - 获取 jQuery 无法识别的表达式错误

javascript - 在 AngularJS 中使用 ng-style 和百分比值设置 HTML 元素宽度

c# - 如何在 "azure function"上模拟 HttpRequest