Skip to content

Instantly share code, notes, and snippets.

@jonasgeiler
Created December 17, 2023 16:20
Show Gist options
  • Save jonasgeiler/12e0ac83b5dd39d0e1720d7aa47ccf3d to your computer and use it in GitHub Desktop.
Save jonasgeiler/12e0ac83b5dd39d0e1720d7aa47ccf3d to your computer and use it in GitHub Desktop.
Super basic implementation of an XML equivalent of JSON.stringify in JavaScript/TypeScript.
const XML = { stringify: (value: any, tag: string) => `<${tag}>` + Object.entries(value).reduce((p, [k, v]) => p + (v && typeof v === 'object' ? XML.stringify(v, k) : `<${k}>${v}</${k}>`), '') + `</${tag}>` };
@jonasgeiler
Copy link
Author

Usage:

XML.stringify({
  "string": "Hello, JSON!",
  "number": 42,
  "boolean": true,
  "nullValue": null,
  "array": [1, 2, 3, "four", false],
  "object": {
    "key1": "value1",
    "key2": 123,
    "key3": {
      "nestedKey1": "nestedValue1",
      "nestedKey2": [1, 2, 3]
    }
  }
}, 'test')

Result:

<test><string>Hello, JSON!</string><number>42</number><boolean>true</boolean><nullValue>null</nullValue><array><0>1</0><1>2</1><2>3</2><3>four</3><4>false</4></array><object><key1>value1</key1><key2>123</key2><key3><nestedKey1>nestedValue1</nestedKey1><nestedKey2><0>1</0><1>2</1><2>3</2></nestedKey2></key3></object></test>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment