【问题标题】:Restructuring JSON before input在输入之前重构 JSON
【发布时间】:2018-02-08 11:38:55
【问题描述】:

这是我的数据库的 JSON 输出中的一个对象示例:

{
    "id": "http://...",
    "type": "example-type",
    "title": "Example title",
    "container-title": "Example container title",
    "page": "1-100",
    "issue": "3",
    "URL": "http://www.url",
    "ISSN": "0123-0123",
    "author": [
        {
            "family": "Smith",
            "given": "John"
        }
    ],
    "issued": {
        "date-parts": [
            [
                "2000"
            ]
        ]
    },
    "keyword": "Sample Tag"
}

在构建数据表时,我在引用作者和日期的嵌套字段时遇到了巨大的困难/错误。我想做的是在表格中使用它之前以某种方式修改/展平它(使用 Datatables 的dataSrc,如here 所述),然后使用datatables API 简单地调用重组数据多次。

所以我现在所说的issued.date-parts.0.0 就是year。结构将改为:

        "authors": "John Smith", "Mark Smith"
        "year": "2000"

【问题讨论】:

  • 有没有办法修改从服务器返回的数据?那将是进行这些更改的最合适的地方。另请注意,authors 的结构在您的第二个示例中仍需要是一个数组。
  • 如果我正确理解了您的评论,我可以做一个$.get 并在将它送到餐桌之前尝试这样做。否则我真的什么也做不了,因为我无法控制 JSON 文件。
  • @east1999 在您的服务器端执行此操作。
  • @Ele 我不认为我在这里有那种选择。需要更多的服务器端语言/工具,我只能运行 html/javascript。
  • 这个数据"year": "1000"来自哪里?

标签: javascript jquery json datatables


【解决方案1】:

使用map函数获取authors

看这段代码sn-p

var data = {    "id": "http://...",    "type": "example-type",    "title": "Example title",    "container-title": "Example container title",    "page": "1-100",    "issue": "3",    "URL": "http://www.url",    "ISSN": "0123-0123",    "author": [        {            "family": "Smith",            "given": "John"        },        {            "family": "Smith",            "given": "Mark"        }    ],    "issued": {        "date-parts": [            [                "2000"            ]        ]    },    "keyword": "Sample Tag"};

var result = {
  "authors": data.author.map((d) => `${d.given} ${d.family}`),
  "year": data.issued['date-parts'][0][0]
}

console.log(result);
.as-console-wrapper {
  max-height: 100% !important
}

【讨论】:

    猜你喜欢
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2017-04-18
    • 2021-10-29
    • 2016-01-27
    • 1970-01-01
    相关资源
    最近更新 更多