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


当前回答

看看jsonpath-object-transform

其他回答

我不太确定是否需要这样做,对我来说,缺乏工具意味着缺乏需求。JSON最好作为对象处理(无论如何在JS中是这样做的),并且您通常使用对象本身的语言来进行转换(Java用于从JSON创建的Java对象,同样用于Perl、Python、Perl、c#、PHP等)。只是普通的赋值(或set, get),循环等等。

我的意思是,XSLT只是另一种语言,需要它的一个原因是XML不是一种对象符号,因此编程语言的对象并不完全匹配(层次结构XML模型和对象/结构之间的阻抗)。

使用XSLT转换JSON是非常可能的:您需要JSON2SAX反序列化器和SAX2JSON序列化器。

Java示例代码: http://www.gerixsoft.com/blog/json/xslt4json

我使用骆驼路由marshal(xmljson) ->到(xlst) -> marshal(xmljson)。足够高效(虽然不是100%完美),但简单,如果你已经在使用Camel。

现在有了!我最近创建了一个库,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属性的对象,输出模型和年份属性。最后一个是递归匹配的恒等变换。

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.