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


当前回答

试着震动。它是一个用Java编写的JSON到JSON转换库。

它是专门创建的,因为我们不想玩“JSON -> XML -> XSLT -> XML -> JSON”的游戏,而且对任何足够复杂的转换使用模板是不可维护的。

其他回答

作为一个老问题的另一个新答案,我建议看看defantjs。它不是JSON的XSLT等价物,它是JSON的XSLT。文档的“模板”部分包括以下示例:

<!-- Defiant template -->
<script type="defiant/xsl-template">
    <xsl:template name="books_template">
        <xsl:for-each select="//movie">
            <xsl:value-of select="title"/><br/>
        </xsl:for-each>
    </xsl:template>
</script>

<script type="text/javascript">

var data = {
        "movie": [
            {"title": "The Usual Suspects"},
            {"title": "Pulp Fiction"},
            {"title": "Independence Day"}
        ]
    },
    htm = Defiant.render('books_template', data);

console.log(htm);
// The Usual Suspects<br>
// Pulp Fiction<br>
// Independence Day<br>

为什么不使用Mr. Data Coverter将JSON转换为XML,然后使用XSLT将其转换为JSON呢?

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

Yate (https://github.com/pasaran/yate)是在XSLT之后专门设计的,具有JPath (JS的自然XPath对等物),可以编译为JavaScript,并且在生产中有相当长的使用历史。它实际上没有记录,但阅读样本和测试应该足够了。

一种尚未给出的方法是使用解析器生成器在XSLT中创建解析器,解析JSON并生成XML输出。

在XML会议上被多次提及的一个选项是ReX解析器生成器(http://www.bottlecaps.de/rex/)——尽管在站点上完全没有文档记载,但是可以通过搜索找到菜谱。