JSON是否有等价的XSLT ?它允许我对JSON进行转换,就像XSLT对XML所做的那样。


当前回答

我最近发现了一个我喜欢的JSON样式工具:https://github.com/twigkit/tempo。非常容易使用的工具——在我看来,使用它比使用XSLT容易得多——不需要XPATH查询。

其他回答

jq——轻量级灵活的命令行JSON处理器

它不像XSLT那样基于模板,但更简洁。例如,将名称和地址字段提取到数组中:[.name, .address]

本教程介绍了一个转换Twitter JSON API的示例(手册中有很多示例)。

看看jsonpath-object-transform

I've been really tired of the enormous amount of JavaScript templating engines out there, and all their inline HTML-templates, different markup styles, etc., and decided to build a small library that enables XSLT formatting for JSON data structures. Not rocket science in any way -- it's just JSON parsed to XML and then formatted with a XSLT document. It's fast too, not as fast as JavaScript template engines in Chrome, but in most other browsers it's at least as fast as the JS engine alternative for larger data structures.

JSLT非常接近于XSLT的JSON等价物。这是一种转换语言,您可以用JSON语法编写输出的固定部分,然后插入表达式来计算您想要插入到模板中的值。

一个例子:

{
  "time": round(parse-time(.published, "yyyy-MM-dd'T'HH:mm:ssX") * 1000),
  "device_manufacturer": .device.manufacturer,
  "device_model": .device.model,
  "language": .device.acceptLanguage
}

它是在Jackson之上用Java实现的。

现在有了!我最近创建了一个库,json-transforms,正是为了这个目的:

https://github.com/ColinEberhardt/json-transforms

它结合使用了JSPath(一种模仿XPath的DSL)和一种直接受到XSLT启发的递归模式匹配方法。

这里有一个简单的例子。给定以下JSON对象:

const json = {
  "automobiles": [
    { "maker": "Nissan", "model": "Teana", "year": 2011 },
    { "maker": "Honda", "model": "Jazz", "year": 2010 },
    { "maker": "Honda", "model": "Civic", "year": 2007 },
    { "maker": "Toyota", "model": "Yaris", "year": 2008 },
    { "maker": "Honda", "model": "Accord", "year": 2011 }
  ]
};

这是一个变换:

const jsont = require('json-transforms');
const rules = [
  jsont.pathRule(
    '.automobiles{.maker === "Honda"}', d => ({
      Honda: d.runner()
    })
  ),
  jsont.pathRule(
    '.{.maker}', d => ({
      model: d.match.model,
      year: d.match.year
    })
  ),
  jsont.identity
];

const transformed  = jsont.transform(json, rules);

输出如下:

{
  "Honda": [
    { "model": "Jazz", "year": 2010 },
    { "model": "Civic", "year": 2007 },
    { "model": "Accord", "year": 2011 }
  ]
}

这个转换由三个规则组成。第一个匹配本田制造的任何汽车,发出一个具有Honda属性的对象,然后递归匹配。第二条规则匹配任何具有maker属性的对象,输出模型和年份属性。最后一个是递归匹配的恒等变换。