npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

jsonify-xml

v1.0.2

Published

A lightweight and efficient library for converting XML to JSON. Perfect for developers needing a simple yet powerful solution to transform XML data structures into JSON format with ease. Ideal for web applications, API integrations, and data parsing workf

Downloads

33

Readme

jsonify-xml

A lightweight and efficient library for converting XML to JSON. Perfect for developers needing a simple yet powerful solution to transform XML data structures into JSON format with ease. Ideal for web applications, API integrations, and data parsing workflows.

It does not parse the following elements:

  • CDATA sections (*)
  • Processing instructions
  • XML declarations
  • Entity declarations
  • Comments

Installation

npm install jsonify-xml

Usage

import { jsonify } from "jsonify-xml";
import path from "path";
import customValueParser from "../src/helpers/customValueParser";

// Option 1: Simple XML string
const jsonResult = jsonify(xmlString);

// Option 2: XML String with custom data parser
const options: JsonifyXMLOptions = {
	xml: xmlString,
	valueParser: customValueParser,
	parseAttributes: true
}
const jsonResult = jsonify(options);

// Option 3: XML file
const options: JsonifyXMLOptions = {
	input: path.join(__dirname, "path/to/xml/file"),
	output: path.join(__dirname, "path/to/json/output")
	valueParser: "string"
}
const jsonResult = jsonify(options);

Options

| Option | Description | Type | | ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------- | | xml | XML content as a string. Required if the input option is not provided. | string | | input | Path to the XML source file. Required if the xml option is not provided. | string | | output | Path to the JSON output file. Optional. | string | | valueParser | Specifies how to parse XML tag or attribute values. It can either be "string", which keeps values in their original string format, or a custom function for custom parsing | "string" \| "default" or function | | parseAttributes | Determines whether to parse attribute values or leave them as strings. Optional. | boolean | | santize | Determines whether special XML characters are replaced with their corresponding ASCII values. Defaults to true. Optional. | boolean |

Special Characters Sanitization

The sanitizing process handles the following special XML characters:

const specialCharsMap = {
    "&": "&",
    '"': """,
    "'": "'",
    "<": "&lt;",
    ">": "&gt;",
    "(": "&#40;",
    ")": "&#41;",
    "#": "&#35;",
    " ": "&#32;",
    "%": "&#37;",
    "+": "&#43;",
    "-": "&#45;",
    ".": "&#46;",
    "/": "&#47;",
    ":": "&#58;",
    ";": "&#59;",
    "=": "&#61;",
    "?": "&#63;",
    "@": "&#64;",
    "[": "&#91;",
    "]": "&#93;",
    "_": "&#95;",
    "`": "&#96;",
    "{": "&#123;",
    "|": "&#124;",
    "}": "&#125;",
    "~": "&#126;",
    "^": "&#94;",
    "\\": "&#92;",
    "$": "&#36;",
    "!": "&#33;",
    "*": "&#42;",
    ",": "&#44;",
    "\n": "&#10;",
    "\r": "&#13;",
    "\t": "&#9;",
    "©": "&#169;",
    "®": "&#174;",
    "¢": "&#162;",
    "£": "&#163;",
    "¥": "&#165;",
    "€": "&#8364;",
    "§": "&#167;",
    "•": "&#8226;",
    "°": "&#176;",
    "¶": "&#182;",
    "∞": "&#8734;",
    "÷": "&#247;",
    "×": "&#215;",
    "±": "&#177;",
    "²": "&#178;",
    "³": "&#179;",
    "¼": "&#188;",
    "½": "&#189;",
    "¾": "&#190;"
};

It also handles decimal and hex numbers using:

const decimalNum = /&#([0-9]+);/g;
const hexNum = /&#x([0-9A-Fa-f]+);/g;

It also handles numeric references, both decimal and hexadecimal, using the following regular expressions:

  • Decimal Numeric References: Matches numeric references like &#65; which represent characters by their decimal Unicode value.
const decimalNum = /&#([0-9]+);/g;
  • Hexadecimal Numeric References: Matches numeric references like &#x41; which represent characters by their hexadecimal Unicode value.
const hexNum = /&#x([0-9A-Fa-f]+);/g;

Example

input.xml

<Order status="active" priority="high" isUrgent="false" itemCount="3">
	<DeliveryPerson>John Doe</DeliveryPerson>
  <IsCanceled>false</IsCanceled>
	<IsDelivered>true</IsDelivered>
	<OrderCode>12345</OrderCode>
	<OrderDate>2024-11-09</OrderDate>
</Order>

index.ts

import path from "path";
import { jsonify, JsonifyXMLOptions, JsonifyResult, Node } from "../src";
import { docs } from "./docs";

const INPUT = path.join(__dirname, "index.xml");
const OUTPUT = path.join(__dirname, "output.json");

const options: JsonifyXMLOptions = {
    input: INPUT,
    output: OUTPUT,
    valueParser,
    parseAttributes: true,
    sanitize: true
};

const [rootName, jsonResult]: JsonifyResult = jsonify(options);
const order: Node = jsonResult[rootName];

console.log(order.attributes.status, result.tagname, result.value, result.nodes.DeliveryPerson.value);

function valueParser(value: string) {
    // Check if value is a boolean
    if (value.toLowerCase() === 'true') return true;
    if (value.toLowerCase() === 'false') return false;
    
    // Check if value is a number
    const num = Number(value);
    if (!isNaN(num)) return num;
    
    // Check if value is a valid date
    const date = Date.parse(value);
    if (!isNaN(date)) return new Date(date);

    // Default case: return the original string
    return value;
}

output.json

[
  "Order",
  {
    "Order": {
      "tagname": "Order",
      "attributes": {
        "status": "active",
        "priority": "high",
        "isUrgent": false,
        "itemCount": 3
      },
      "nodes": {
        "DeliveryPerson": {
          "tagname": "DeliveryPerson",
          "value": "John Doe"
        },
        "IsCanceled": {
          "tagname": "IsCanceled",
          "value": false
        },
        "IsDelivered": {
          "tagname": "IsDelivered",
          "value": true
        },
        "OrderCode": {
          "tagname": "OrderCode",
          "value": 12345
        },
        "OrderDate": {
          "tagname": "OrderDate",
          "value": "2024-11-09T00:00:00.000Z"
        }
      }
    }
  }
]