JSON的XSLT等价物

luv*_*ere 393 xslt json language-comparisons equivalent

是否有JSON 的XSLT等价物?允许我对XSON进行转换的事情,比如XSLT对XML做的转换.

jsc*_*sse 81

JSON的XSLT等价物 - 候选列表(工具和规格)

工具

  1. XSLT

    您可以使用XSLT for JSON,目的是fn:json-to-xml.

    本节介绍允许使用XSLT处理JSON数据的工具.

  2. jq最后一次提交2018年5月12日

    jq就像是用于JSON数据的sed - 你可以用它来切片和过滤,映射和转换结构化数据,同样方便sed,awk,grep和朋友让你玩文本.有不同操作系统的安装包.

  3. jj最后一次提交2018年3月2日

    JJ是一个命令行实用程序,它提供了一种快速简单的方法来从JSON文档中检索或更新值.它由GJSON和SJSON提供支持.

  4. fx最后一次提交2018年3月20日

    命令行JSON处理工具

    • 不需要学习新语法
    • 简单的JavaScript
    • 格式化和突出显示
    • 独立二进制
  5. jsawk最后提交2015年3月4日

    Jsawk就像awk,但对于JSON.您使用从stdin读取的JSON对象数组,使用JavaScript过滤它们以生成打印到stdout的结果数组.

  6. json Last Commit 2017年3月3日

    json是一个使用JSON的快速CLI工具.它是一个单文件node.js脚本,没有外部deps(除了node.js本身).

  7. jl Last Commit Apr 10,2018

    jl("JSON lambda")是一种用于查询和操作JSON的微型函数语言.

  8. yate Last Commit 2017年3月13日

    测试可以用作文档https://github.com/pasaran/yate/tree/master/tests

  9. json-transforms Last Commit Dec 1,2017

    提供用于转换JSON数据的递归模式匹配方法.转换被定义为一组与JSON对象的结构匹配的规则.当匹配发生时,规则发出转换的数据,可选地递归以转换子对象.

  10. jsonpath-object-transform最后提交2017年1月18日

    使用JSONPath从对象文字中提取数据,并基于模板生成新对象.

  11. JOLT Last Commit,2018年5月1日

    用Java编写的JSON到JSON转换库,其中转换的"规范"本身就是一个JSON文档.

  12. gron Last Commit Apr 5,2018

    使JSON可以抓取!gron将JSON转换为离散的赋值,以便更容易地为您想要的内容进行grep,并查看它的绝对"路径".它简化了对返回大量JSON但具有可怕文档的API的探索.

  13. Stapling Last Commit 2013年9月16日

    Stapling是一个JavaScript库,可以为JSON对象启用XSLT格式.Stapling不是使用JavaScript模板引擎和text/html模板,而是让您有机会使用XSLT模板 - 与Ajax异步加载,然后缓存客户端 - 来解析您的JSON数据源.

  14. json-e最后提交2018年5月22日

    JSON-e是一个数据结构参数化系统,用于在JSON对象中嵌入上下文.中心思想是将数据结构视为"模板",并使用另一种数据结构作为上下文对其进行转换,以生成输出数据结构.

  15. JSLT

    JSLT是JSON的完整查询和转换语言.语言设计的灵感来自jq,XPath和XQuery.

眼镜:

  • JsonPointer

    JSON指针定义了一种字符串语法,用于标识JavaScript Object Notation(JSON)文档中的特定值.

  • JsonPath

    JSONPath表达式始终引用JSON结构,其方式与XPath表达式与XML文档结合使用的方式相同

  • JSPath

    用于JSON的JSPath就像XPath for XML."

  • JSONiq

    JSONiq背后的主要灵感来源是XQuery,它已被证明是迄今为止用于半结构化数据的成功且高效的查询语言

  • 感谢您的非常详细和有用的帖子。为了将单行 json 转换为可读形式,jq(列表中的 nr.2)对我来说是最佳选择。再次感谢! (2认同)

Tim*_*Tim 74

有趣的想法.一些在Google上搜索产生了一些感兴趣的页面,包括:

希望这可以帮助.

  • 是的,谢谢,这就是我在寻找的东西.遗憾的是这种技术并不是更受欢迎,JSON经常被用作REST风格服务的返回格式,并且有一种标准的方法来实现转换. (10认同)
  • 此代码使用string.eval()... :-( (7认同)

Mil*_*o S 67

试试JOLT.它是用Java编写的JSON to JSON转换库.

它是专门创建的,因为我们不想播放"JSON - > XML - > XSLT - > XML - > JSON"游戏,并且使用模板进行任何足够复杂的转换都是不可维护的.

  • +9000:这是一个严肃的项目!好哇.带有示例的在线演示大大有助于攀登学习曲线:http://jolt-demo.appspot.com/ (3认同)

小智 15

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

  • 如果转换的最终结果是HTML,Tempo看起来很棒.但是如果你只是想将一个隐含的结构重新排列成另一个结构,那么最终结果仍然是**JSON.我仍然想要一个XPath的模拟,所以我可以以功能的方式编写转换. (9认同)

13r*_*ren 15

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

它不像XSLT那样基于模板,但更简洁.例如,提取nameaddress字段到数组:[.name, .address]

教程将介绍转换Twitter的JSON API的示例(该手册有很多示例).

  • 它更简洁,因为它能够少得多. (4认同)

Cha*_*pul 15

XSLT支持JSON,如http://www.w3.org/TR/xslt-30/#json所示

XML使用尖括号作为分隔符标记,JSON使用大括号,方括号,...... I. e.XML更少的令牌识别比较意味着它针对声明性转换进行了优化,而更多的比较,如switch语句,出于速度原因,假设推测分支预测脚本语言中的命令性代码是有用的.直接结果是,对于半结构化数据的不同组合,您可能希望将XSLT和javascript引擎的性能作为响应式页面的一部分进行基准测试.对于可忽略的数据有效负载,转换可能与没有XML序列化的JSON一样好.W3的决定应该基于更好的分析.


Ric*_*ick 11

说缺乏工具表明缺乏需求只是乞求这个问题.同样可以用于支持Linux中的X或Y(为什么要为这样的少数操作系统开发高质量的驱动程序和/或游戏?为什么要关注大型游戏和硬件公司不开发的操作系统?).可能需要使用XSLT和JSON的人最终会使用一些简单的解决方法:将JSON转换为XML.但这不是最佳解决方案,是吗?

当你有一个原生的JSON格式,并且你想在浏览器中编辑它"wysywyg"时,XSLT对于这个问题来说是一个绰绰有余的解决方案.使用传统的javascript编程实现这一点可能会成为一种痛苦.

实际上,我已经对XSLT实现了"石器时代"的方法,使用子串解析来解释javascript的一些基本命令,比如调用模板,处理子进程等.当然,使用JSON对象实现转换引擎要比实现一个完整的XML解析器来解析XSLT.问题是,要使用XML模板转换JSON对象,需要解析模板的XML.

要使用XML(或HTML,或文本或其他)转换JSON对象,您需要仔细考虑语法以及需要使用哪些特殊字符来标识转换命令.否则,您最终将不得不为自己的自定义模板语言设计解析器.走过这条路,我可以告诉你,它并不漂亮.

更新(2010年11月12日):经过几周的解析器工作,我已经能够优化它.事先解析模板,并将命令存储为JSON对象.转换规则也是JSON对象,而模板代码是HTML和类似于shell代码的自制语法的混合.我已经能够将复杂的JSON文档转换为HTML以制作文档编辑器.代码大约是1K行的编辑器(它是私有项目所以我不能共享它)和大约990行的JSON转换代码(包括迭代命令,简单比较,模板调用,变量保存和评估).我计划在MIT许可下发布它.如果你想参与,请给我发邮件.


YSh*_*arp 11

我最近在这周围写了我自己的小型图书馆,试图保持尽可能接近

5.1处理模型(XSLT REC) https://www.w3.org/TR/xslt#section-Processing-Model

在可能的情况下(尽我所能),在几行JavaScript代码中.

以下是一些使用不完全无关的例子......

1. JSON-to-some-markup:

小提琴:https://jsfiddle.net/YSharpLanguage/kj9pk8oz/10

(受D.1文档示例(XSLT REC) 启发https://www.w3.org/TR/xslt#section-Document-Example)

这个:

var D1document = {
    type: "document", title: [ "Document Title" ],
    "": [
      { type: "chapter", title: [ "Chapter Title" ],
        "": [
        { type: "section", title: [ "Section Title" ],
          "": [
            { type: "para", "": [ "This is a test." ] },
            { type: "note", "": [ "This is a note." ] }
        ] },
        { type: "section", title: [ "Another Section Title" ],
          "": [
            { type: "para", "": [ "This is ", { emph: "another" }, " test." ] },
            { type: "note", "": [ "This is another note." ] }
        ] }
      ] }
    ] };

var D1toHTML = { $: [
  [ [ function(node) { return node.type === "document"; } ],
    function(root) {
      return "<html>\r\n\
  <head>\r\n\
    <title>\r\n\
      {title}\r\n".of(root) + "\
    </title>\r\n\
  </head>\r\n\
  <body>\r\n\
{*}".of(root[""].through(this)) + "\
  </body>\r\n\
</html>";
    }
  ],
  [ [ function(node) { return node.type === "chapter"; } ],
    function(chapter) {
      return "    <h2>{title}</h2>\r\n".of(chapter) + "{*}".of(chapter[""].through(this));
    }
  ],
  [ [ function(node) { return node.type === "section"; } ],
    function(section) {
      return "    <h3>{title}</h3>\r\n".of(section) + "{*}".of(section[""].through(this));
    }
  ],
  [ [ function(node) { return node.type === "para"; } ],
    function(para) {
      return "    <p>{*}</p>\r\n".of(para[""].through(this));
    }
  ],
  [ [ function(node) { return node.type === "note"; } ],
    function(note) {
      return '    <p class="note"><b>NOTE: </b>{*}</p>\r\n'.of(note[""].through(this));
    }
  ],
  [ [ function(node) { return node.emph; } ],
    function(emph) {
      return "<em>{emph}</em>".of(emph);
    }
  ]
] };

console.log(D1document.through(D1toHTML));
Run Code Online (Sandbox Code Playgroud)

......给出:

<html>
  <head>
    <title>
      Document Title
    </title>
  </head>
  <body>
    <h2>Chapter Title</h2>
    <h3>Section Title</h3>
    <p>This is a test.</p>
    <p class="note"><b>NOTE: </b>This is a note.</p>
    <h3>Another Section Title</h3>
    <p>This is <em>another</em> test.</p>
    <p class="note"><b>NOTE: </b>This is another note.</p>
  </body>
</html>
Run Code Online (Sandbox Code Playgroud)

2. JSON-to-JSON:

小提琴:https://jsfiddle.net/YSharpLanguage/ppfmmu15/10

这个:

// (A "Company" is just an object with a "Team")
function Company(obj) {
  return obj.team && Team(obj.team);
}

// (A "Team" is just a non-empty array that contains at least one "Member")
function Team(obj) {
  return ({ }.toString.call(obj) === "[object Array]") &&
         obj.length &&
         obj.find(function(item) { return Member(item); });
}

// (A "Member" must have first and last names, and a gender)
function Member(obj) {
  return obj.first && obj.last && obj.sex;
}

function Dude(obj) {
  return Member(obj) && (obj.sex === "Male");
}

function Girl(obj) {
  return Member(obj) && (obj.sex === "Female");
}

var data = { team: [
  { first: "John", last: "Smith", sex: "Male" },
  { first: "Vaio", last: "Sony" },
  { first: "Anna", last: "Smith", sex: "Female" },
  { first: "Peter", last: "Olsen", sex: "Male" }
] };

var TO_SOMETHING_ELSE = { $: [

  [ [ Company ],
    function(company) {
      return { some_virtual_dom: {
        the_dudes: { ul: company.team.select(Dude).through(this) },
        the_grrls: { ul: company.team.select(Girl).through(this) }
      } }
    } ],

  [ [ Member ],
    function(member) {
      return { li: "{first} {last} ({sex})".of(member) };
    } ]

] };

console.log(JSON.stringify(data.through(TO_SOMETHING_ELSE), null, 4));
Run Code Online (Sandbox Code Playgroud)

......给出:

{
    "some_virtual_dom": {
        "the_dudes": {
            "ul": [
                {
                    "li": "John Smith (Male)"
                },
                {
                    "li": "Peter Olsen (Male)"
                }
            ]
        },
        "the_grrls": {
            "ul": [
                {
                    "li": "Anna Smith (Female)"
                }
            ]
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

3. XSLT与JavaScript:

相当于......的JavaScript

XSLT 3.0 REC第14.4节示例:基于公共值对节点进行分组

(at:http://jsfiddle.net/YSharpLanguage/8bqcd0ey/1)

参看 https://www.w3.org/TR/xslt-30/#grouping-examples

哪里...

var cities = [
  { name: "Milano",  country: "Italia",      pop: 5 },
  { name: "Paris",   country: "France",      pop: 7 },
  { name: "München", country: "Deutschland", pop: 4 },
  { name: "Lyon",    country: "France",      pop: 2 },
  { name: "Venezia", country: "Italia",      pop: 1 }
];

/*
  Cf.
  XSLT 3.0 REC Section 14.4
  Example: Grouping Nodes based on Common Values

  https://www.w3.org/TR/xslt-30/#grouping-examples
*/
var output = "<table>\r\n\
  <tr>\r\n\
    <th>Position</th>\r\n\
    <th>Country</th>\r\n\
    <th>City List</th>\r\n\
    <th>Population</th>\r\n\
  </tr>{*}\r\n\
</table>".of
  (
    cities.select().groupBy("country")(function(byCountry, index) {
      var country = byCountry[0],
          cities = byCountry[1].select().orderBy("name");
      return "\r\n\
  <tr>\r\n\
    <td>{position}</td>\r\n\
    <td>{country}</td>\r\n\
    <td>{cities}</td>\r\n\
    <td>{population}</td>\r\n\
  </tr>".
        of({ position: index + 1, country: country,
             cities: cities.map(function(city) { return city.name; }).join(", "),
             population: cities.reduce(function(sum, city) { return sum += city.pop; }, 0)
           });
    })
  );
Run Code Online (Sandbox Code Playgroud)

......给出:

<table>
  <tr>
    <th>Position</th>
    <th>Country</th>
    <th>City List</th>
    <th>Population</th>
  </tr>
  <tr>
    <td>1</td>
    <td>Italia</td>
    <td>Milano, Venezia</td>
    <td>6</td>
  </tr>
  <tr>
    <td>2</td>
    <td>France</td>
    <td>Lyon, Paris</td>
    <td>9</td>
  </tr>
  <tr>
    <td>3</td>
    <td>Deutschland</td>
    <td>München</td>
    <td>4</td>
  </tr>
</table>
Run Code Online (Sandbox Code Playgroud)

4. JSONiq与JavaScript:

相当于......的JavaScript

JSONiq用例第1.1.2节.为JSON分组查询

(at:https://jsfiddle.net/YSharpLanguage/hvo24hmk/3)

参看 http://jsoniq.org/docs/JSONiq-usecases/html-single/index.html#jsongrouping

哪里...

/*
  1.1.2. Grouping Queries for JSON
  http://jsoniq.org/docs/JSONiq-usecases/html-single/index.html#jsongrouping
*/
var sales = [
  { "product" : "broiler", "store number" : 1, "quantity" : 20  },
  { "product" : "toaster", "store number" : 2, "quantity" : 100 },
  { "product" : "toaster", "store number" : 2, "quantity" : 50 },
  { "product" : "toaster", "store number" : 3, "quantity" : 50 },
  { "product" : "blender", "store number" : 3, "quantity" : 100 },
  { "product" : "blender", "store number" : 3, "quantity" : 150 },
  { "product" : "socks", "store number" : 1, "quantity" : 500 },
  { "product" : "socks", "store number" : 2, "quantity" : 10 },
  { "product" : "shirt", "store number" : 3, "quantity" : 10 }
];

var products = [
  { "name" : "broiler", "category" : "kitchen", "price" : 100, "cost" : 70 },
  { "name" : "toaster", "category" : "kitchen", "price" : 30, "cost" : 10 },
  { "name" : "blender", "category" : "kitchen", "price" : 50, "cost" : 25 },
  {  "name" : "socks", "category" : "clothes", "price" : 5, "cost" : 2 },
  { "name" : "shirt", "category" : "clothes", "price" : 10, "cost" : 3 }
];

var stores = [
  { "store number" : 1, "state" : "CA" },
  { "store number" : 2, "state" : "CA" },
  { "store number" : 3, "state" : "MA" },
  { "store number" : 4, "state" : "MA" }
];

var nestedGroupingAndAggregate = stores.select().orderBy("state").groupBy("state")
( function(byState) {
    var state = byState[0],
        stateStores = byState[1];
    byState = { };
    return (
      (
        byState[state] =
        products.select().orderBy("category").groupBy("category")
        ( function(byCategory) {
            var category = byCategory[0],
                categoryProducts = byCategory[1],
                categorySales = sales.filter(function(sale) {
                  return stateStores.find(function(store) { return sale["store number"] === store["store number"]; }) &&
                         categoryProducts.find(function(product) { return sale.product === product.name; });
                });
            byCategory = { };
            return (
              (
                byCategory[category] =
                categorySales.select().orderBy("product").groupBy("product")
                ( function(byProduct) {
                    var soldProduct = byProduct[0],
                        soldQuantities = byProduct[1];
                    byProduct = { };
                    return (
                      (
                        byProduct[soldProduct] =
                        soldQuantities.reduce(function(sum, sale) { return sum += sale.quantity; }, 0)
                      ),
                      byProduct
                    );
                } ) // byProduct()
              ),
              byCategory
            );
        } ) // byCategory()
      ),
      byState
    );
} ); // byState()
Run Code Online (Sandbox Code Playgroud)

......给出:

[
  {
    "CA": [
      {
        "clothes": [
          {
            "socks": 510
          }
        ]
      },
      {
        "kitchen": [
          {
            "broiler": 20
          },
          {
            "toaster": 150
          }
        ]
      }
    ]
  },
  {
    "MA": [
      {
        "clothes": [
          {
            "shirt": 10
          }
        ]
      },
      {
        "kitchen": [
          {
            "blender": 250
          },
          {
            "toaster": 50
          }
        ]
      }
    ]
  }
]
Run Code Online (Sandbox Code Playgroud)

克服JSONPath wrt的局限性也很有用.通过这个SO问题(当然还有其他人)提出的对祖先轴的查询.

例如,如何获得知道其品牌ID的杂货商品的折扣

{
 "prods": [
    {
        "info": {
              "rate": 85
                },
        "grocery": [
                 {
                  "brand": "C",
                  "brand_id": "984"
                 },
                 {
                  "brand": "D",
                  "brand_id": "254"
                 }
                 ],
         "discount": "15"
    },
    {
        "info": {
              "rate": 100
                },
        "grocery": [
                 {
                  "brand": "A",
                  "brand_id": "983"
                 },
                 {
                  "brand": "B",
                  "brand_id": "253"
                 }
                 ],
         "discount": "20"
     }
 ]
}
Run Code Online (Sandbox Code Playgroud)

可能的解决方案是:

var products = {
     "prods": [
        {
            "info": {
                  "rate": 85
                    },
            "grocery": [
                     {
                      "brand": "C",
                      "brand_id": "984"
                     },
                     {
                      "brand": "D",
                      "brand_id": "254"
                     }
                     ],
             "discount": "15"
        },
        {
            "info": {
                  "rate": 100
                    },
            "grocery": [
                     {
                      "brand": "A",
                      "brand_id": "983"
                     },
                     {
                      "brand": "B",
                      "brand_id": "253"
                     }
                     ],
             "discount": "20"
         }
     ]
};

function GroceryItem(obj) {
  return (typeof obj.brand === "string") && (typeof obj.brand_id === "string");
}

    // last parameter set to "true", to grab all the "GroceryItem" instances
    // at any depth:
var itemsAndDiscounts = [ products ].nodeset(GroceryItem, true).
    map(
      function(node) {
        var item = node.value, // node.value: the current "GroceryItem" (aka "$.prods[*].grocery[*]")

            discount = node.parent. // node.parent: the array of "GroceryItem" (aka "$.prods[*].grocery")
                       parent. // node.parent.parent: the product (aka "$.prods[*]")
                       discount; // node.parent.parent.discount: the product discount

        // finally, project into an easy-to-filter form:
        return { id: item.brand_id, discount: discount };
      }
    ),
    discountOfItem983;

discountOfItem983 = itemsAndDiscounts.
  filter
  (
    function(mapped) {
      return mapped.id === "983";
    }
  )
  [0].discount;

console.log("Discount of #983: " + discountOfItem983);
Run Code Online (Sandbox Code Playgroud)

... 这使:

Discount of #983: 20
Run Code Online (Sandbox Code Playgroud)

"HTH,


Col*_*inE 10

现在有!我最近创建了一个库,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 }
  ]
};
Run Code Online (Sandbox Code Playgroud)

这是一个转变:

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);
Run Code Online (Sandbox Code Playgroud)

哪个输出如下:

{
  "Honda": [
    { "model": "Jazz", "year": 2010 },
    { "model": "Civic", "year": 2007 },
    { "model": "Accord", "year": 2011 }
  ]
}
Run Code Online (Sandbox Code Playgroud)

该变换由三个规则组成.第一个匹配任何由本田制造的汽车,发射具有Honda财产的物体,然后递归匹配.第二个规则将任何对象与maker属性匹配,输出modelyear属性.最后是递归匹配的身份转换.


L S*_*L S 9

作为旧问题的另一个新答案,我建议看一下DefiantJS.它不是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>
Run Code Online (Sandbox Code Playgroud)


Bjö*_*örn 5

我真的已经厌倦了那里大量的JavaScript模板引擎以及它们的所有内联HTML模板,不同的标记样式等,并决定建立一个小型库来为JSON数据结构实现XSLT格式化。绝不是火箭科学,它只是将JSON解析为XML,然后使用XSLT文档进行格式化。它的速度也很快,不及Chrome中的JavaScript模板引擎快,但在大多数其他浏览器中,它至少与大型数据结构的JS引擎替代品一样快。