<json-to-xml>

JSON to XML converter

Core v2.2.0

Overview

The processor converts JSON data (from REST APIs, files, etc.) into well-formed XML. This enables you to use XPath and XQuery to extract data from JSON responses, providing a unified query language for both HTML and JSON sources.

Usage Examples

Example 1: Parse JSON API response

example-1.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<def var="userName">
  <xpath expression="//user/name/text()">
    <json-to-xml>
      <http url="https://api.example.com/user/123">
        <http-header name="Accept">application/json</http-header>
      </http>
    </json-to-xml>
  </xpath>
</def>
</config>

Example 2: Extract from nested JSON

example-2.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<!-- JSON: {"data": {"users": [{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}]}} -->
<def var="userNames">
  <xpath expression="//users/item/name/text()">
    <json-to-xml>
      <http url="https://api.example.com/users"/>
    </json-to-xml>
  </xpath>
</def>

<!-- Result: List of names -->
<loop item="name">
  ${userNames}
  
  <file path="names.txt" action="append">${name}&#10;</file>
</loop>
</config>

Example 3: JSON array processing

example-3.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<!-- JSON: [{"id": 1, "title": "Post 1"}, {"id": 2, "title": "Post 2"}] -->
<loop item="post">
  <xpath expression="//item">
    <json-to-xml>
      <http url="https://api.example.com/posts"/>
    </json-to-xml>
  </xpath>
  
  <def var="postId"><xpath expression="id/text()">${post}</xpath></def>
  <def var="postTitle"><xpath expression="title/text()">${post}</xpath></def>
  
  <file path="posts/post-${postId}.txt" action="write">
    ${postTitle}
  </file>
</loop>
</config>

Example 4: Complex nested data extraction

example-4.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<def var="addresses">
  <xpath expression="//users/item[address/city/text()='London']/address/street/text()">
    <json-to-xml>
      <http url="https://api.example.com/users"/>
    </json-to-xml>
  </xpath>
</def>
</config>

Example 5: Custom root tag name

example-5.xml
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns="http://org.webharvest/schema/2.1/core">
<json-to-xml tag="root">
  <http url="https://api.example.com/data"/>
</json-to-xml>
<!-- Output: <root>...</root> instead of default <json>...</json> -->
</config>

Important Notes

Related Processors