{"id":23231679,"url":"https://github.com/danielduarte/xml2json-canonical","last_synced_at":"2025-04-05T19:29:22.039Z","repository":{"id":57401875,"uuid":"273586247","full_name":"danielduarte/xml2json-canonical","owner":"danielduarte","description":"XML to JSON converter preserving everything from the original XML in a canonical JSON representation easy to work with - Node.js module and CLI tool","archived":false,"fork":false,"pushed_at":"2024-06-16T12:22:40.000Z","size":37,"stargazers_count":1,"open_issues_count":3,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-13T21:37:08.994Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/danielduarte.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-06-19T21:04:37.000Z","updated_at":"2022-11-13T01:04:04.000Z","dependencies_parsed_at":"2023-01-22T23:45:22.957Z","dependency_job_id":null,"html_url":"https://github.com/danielduarte/xml2json-canonical","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielduarte%2Fxml2json-canonical","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielduarte%2Fxml2json-canonical/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielduarte%2Fxml2json-canonical/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/danielduarte%2Fxml2json-canonical/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/danielduarte","download_url":"https://codeload.github.com/danielduarte/xml2json-canonical/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247390337,"owners_count":20931402,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-12-19T02:15:34.032Z","updated_at":"2025-04-05T19:29:22.011Z","avatar_url":"https://github.com/danielduarte.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# xml2json-canonical :zap:\n\nAn XML to JSON converter that preserves everything from the original XML in a canonical JSON representation easy to work with, modify, and convert back to XML.\n\n## Features\n\n- [Conversion from XML to canonical JSON](#api).\n- [Conversion from canonical JSON to XML](#api).\n- [Conversion from strings or files, sync or async](#api).\n- [Configurable output](#options).\n- [CLI tool from the command line](#as-cli-console-tool).\n- [Available as a Node.js or Deno module](#as-a-module).\n\n\n## Quickstart\n\n### As a module\n\n#### Install\n\n```Shell\nnpm i xml2json-canonical\n```\n\n#### Use\n\n```JavaScript\nconst { toJson } = require('xml2json-canonical');\n\nconst xml = `\n  \u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n  \u003cproject version=\"1.0.2\"\u003e\n    \u003ccomponent name=\"example\" anotherAttr=\"some value\" /\u003e\n    \u003cmore\u003etext\u003c/more\u003e\n  \u003c/project\u003e\n`;\n\nconst json = toJson(xml, 'compact');\n\nconsole.log(json);\n```\n\n\u003e Output:\n```JavaScript\n{\n  type: 'xml',\n  content: {\n    type: 'element',\n    name: 'project',\n    attrs: { version: '1.0.2' },\n    content: [\n      {\n        type: 'element',\n        name: 'component',\n        attrs: { name: 'example', anotherAttr: 'some value' },\n        selfClosing: true\n      },\n      {\n        type: 'element',\n        name: 'more',\n        content: 'text',\n        selfClosing: false\n      }\n    ],\n    selfClosing: false\n  }\n}\n```\n\nThis is a condensed output obtained using the profile `'compact'`. Check [other profiles](#profiles).\n\n\n### As CLI (console tool)\n\n#### Install globally\n\n```Shell\nnpm i -g xml2json-canonical\n```\n\n#### Use\n\n```Shell\nxml2json [--pretty] [--profile=strict|simple|compact] file1.xml file2.xml [... more files]\n```\n\n## API\n\n| Function                     | Details                                                                                                                                              |\n|------------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------|\n| **toJson**(xmlStr)               | Converts an XML string into JSON. See [options](#options) to configure conversions.                                                                              |\n| **toJsonFromFile**(filepath)     | Converts an XML file into JSON returning a Promise for async programming. See [options](#options) to configure conversions.                                      |\n| **toJsonFromFileSync**(filepath) | Converts an XML file into JSON synchronously. See [options](#options) to configure conversions.                                                                 |\n| **toXml**(jsObject)              | Converts a JavaScript object into XML. The object must be in the canonical XML format, which is the returned format by any of the previous functions. |\n\n## Options\n\nYou can customize several details of the output, or just [GO TO ACTION](#profiles).\n\nTo customize the JSON output, all the functions to convert from XML to JSON (`toJson`, `toJsonFromFile`, `toJsonFromFileSync`) have the same possible set of options as an object in the second parameter. None of them are mandatory and all have a default value.\n\n```JavaScript\nconst json = toJson(xml, {\n  skipEmptyTexts: [boolean],\n  textNodesToStr: [boolean],\n  extractOnlyChilds: [boolean],\n  omitEmptyAttrs: [boolean],\n  omitEmptyContent: [boolean],\n  reportError: (msg: [string]) =\u003e { /* your custom code */ },\n});\n```\n\n| Option | Default | Details |\n|--|--|--|\n| **skipEmptyTexts** [_boolean_] | `false` | If `true`, text nodes formed only by whitespace characters (CR, LR, tabs and spaces) are ignored. |\n| **textNodesToStr** [_boolean_] | `false` | If `true`, text nodes are returned as strings. If `false`, pure canonical form is preserved. |\n| **extractOnlyChilds** [_boolean_] | `false` | If `true`, elements with a single child node have that only child directly in the field `content` without having an array with that only element. If `false`, pure canonical form is preserved. |\n| **omitEmptyAttrs** [_boolean_] | `false` | If `true`, elements with no attributes omit the field `attrs`. Otherwise, the field `attrs` is included with an empty object (`attrs: {}`) preserving pure canonical form. |\n| **omitEmptyContent** [_boolean_] | `false` | If `true`, elements with no children nodes omit the field `content`. Otherwise the field `content` is included with an empty array (`content: []`) preserving pure canonical form. |\n| **reportError** [_function: (msg: string)_=\u003e {}] | Errors are printed out to the standard error output | Callback to receive parsing errors. It is executed on every error passing a descriptive message. To ignore errors set it to `() =\u003e {}`. |\n\n\n## Profiles\n\nUse a profile name as second parameter instead of specifying options:\n```JavaScript\ntoJson(xml, 'simple');\n```\n\n### Profile: 'compact'\n\n```JavaScript\nconst json = toJson(xml, 'compact');\n```\nThe most compact representation in JSON format. Take into account that this profile looses the text nodes that are purely composed by whitespace characters (LR, CR, tabs and spaces), which are in most cases not used. To keep those strings in the result use the default options (omitting the second parameter), or use another profile like `'strict'`. Also you can specify customized options instead of profiles as the second parameter and set `skipEmptyTexts: false`.\n\n\u003e Output:\n```JavaScript\n{\n  type: 'xml',\n  content: {\n    type: 'element',\n    name: 'project',\n    attrs: { version: '1.0.2' },\n    content: [\n      {\n        type: 'element',\n        name: 'component',\n        attrs: { name: 'example', anotherAttr: 'some value' },\n        selfClosing: true\n      },\n      {\n        type: 'element',\n        name: 'more',\n        content: 'text',\n        selfClosing: false\n      }\n    ],\n    selfClosing: false\n  }\n}\n```\n\n### Profile: 'simple'\n\n```JavaScript\nconst json = toJson(xml, 'simple');\n```\nSimilar to `'compact'` but purely canonical, which makes it easier to process.\n\nThis profile ensures that all fields are always present, and they are always of the same type:\n\n- Even when an element does not have attributes, the field `attrs` is present as `attrs: {}`.\n- Even when an element does not have children nodes, the field `content` is present as `content: [],`.\n- Even when an element has a single child, it is returned in the field `content` as an array element. So, instead of `content: { ... the node... }`, the result is `content: [{ ... the node... }]`.\n- Text nodes are always returned as canonical nodes like `{ type: 'text', content: 'some text' }` instead of returning a string like `'some text'`.\n\n\u003e Output:\n```JavaScript\n{\n  type: 'xml',\n  content: [\n    {\n      type: 'element',\n      name: 'project',\n      attrs: { version: '1.0.2' },\n      content: [\n        {\n          type: 'element',\n          name: 'component',\n          attrs: { name: 'example', anotherAttr: 'some value' },\n          content: [],\n          selfClosing: true\n        },\n        {\n          type: 'element',\n          name: 'more',\n          attrs: {},\n          content: [ { type: 'text', content: 'text' } ],\n          selfClosing: false\n        }\n      ],\n      selfClosing: false\n    }\n  ]\n}\n```\n\n### Profile: 'strict' _(default)_\n\n```JavaScript\nconst json = toJson(xml); // Omitted since it's the default profile\n```\nSimilar to `'simple'` but including the text nodes that are purely formed by whitespace characters.\n\nUseful to preserve XML indentation and values formed by only spaces.\n\n\u003e Output:\n```JavaScript\n{\n  type: 'xml',\n  content: [\n    { type: 'text', content: '\\n  ' },\n    {\n      type: 'element',\n      name: 'project',\n      attrs: { version: '1.0.2' },\n      content: [\n        { type: 'text', content: '\\n    ' },\n        {\n          type: 'element',\n          name: 'component',\n          attrs: { name: 'example', anotherAttr: 'some value' },\n          content: [],\n          selfClosing: true\n        },\n        { type: 'text', content: '\\n    ' },\n        {\n          type: 'element',\n          name: 'more',\n          attrs: {},\n          content: [ { type: 'text', content: 'text' } ],\n          selfClosing: false\n        },\n        { type: 'text', content: '\\n  ' }\n      ],\n      selfClosing: false\n    },\n    { type: 'text', content: '\\n' }\n  ]\n}\n```\n\n## Notes\n\n- Note that the resulting outputs are JavaScript objects for easy manipulation, which means that if you need the actual JSON string representation, you have to call `JSON.stringity(...)`.\n\n- When converting from XML to JSON and back to XML, in most cases the result is exactly the same as the original input, except for some edge cases where it is equivalent but with slight differences:\n  - *Case 1*: Only one space between attributes is preserved: \u003ccode\u003e\u0026lt;elem\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026nbsp;attr1=\"val1\"\u0026nbsp;\u0026nbsp;\u0026nbsp;attr2=\"val2\"\u0026nbsp;\u0026nbsp;\u0026nbsp;\u0026gt;\u003c/code\u003e is converted to `\u003celem attr1=\"val1\" attr2=\"val2\"\u003e`.\n  - *Case 2*: Self-closing elements have always an space before close: `\u003celem/\u003e` is converted to `\u003celem /\u003e`.\n\n## Future\n\n- Add option to auto-stringify output.\n- Convert to XML from JSON strings.\n- [Suggest your own idea](https://github.com/danielduarte/xml2json-canonical/issues/new).\n\n## Having issues?\n\nFeel free to report any issues :bug: or feature request :bulb: in [Github repo](https://github.com/danielduarte/xml2json-canonical/issues/new).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanielduarte%2Fxml2json-canonical","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdanielduarte%2Fxml2json-canonical","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdanielduarte%2Fxml2json-canonical/lists"}