Skip to content

Commit

Permalink
Merge pull request #1010 from LindaWang7/main
Browse files Browse the repository at this point in the history
JSON to XML Converter
  • Loading branch information
pawangeek authored Dec 18, 2024
2 parents bcdccd5 + 3d918a4 commit 54f41dc
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 0 deletions.
39 changes: 39 additions & 0 deletions json_to_xml/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
# JSON to XML Converter

A standalone Python script that converts a JSON file into an XML file. This script is useful for transforming JSON data into a structured XML format for use in systems that require XML-based input.

## Features

- Reads JSON data from a file.
- Converts nested JSON objects and arrays into XML elements.
- Outputs well-structured XML files with proper formatting and indentation.
- Adds a standard XML declaration header (`<?xml version="1.0" encoding="UTF-8"?>`).

## Setup Instructions

### Prerequisites
- Python 3.6 or later installed on your system.

### Installation
1. Clone or download this script to your local system.
2. Save the JSON data you want to convert in a file named `input.json` in the same directory as the script.

### Running the Script
1. Open a terminal or command prompt.
2. Navigate to the directory containing the script.
3. Run the script using the following command:
```bash
python json_to_xml.py
The script will generate an XML file named output.xml in the same directory.

## Output

Display images/gifs/videos of output/result of your script so that users can visualize it

## Author(s)

LindaWang7

## Disclaimers, if any

N/A
63 changes: 63 additions & 0 deletions json_to_xml/json_to_xml.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import json


def json_to_xml(json_obj, line_padding=""):
"""
Convert a JSON object to an XML string.
"""
result_list = []

if isinstance(json_obj, dict):
for key, value in json_obj.items():
result_list.append(f"{line_padding}<{key}>")
result_list.append(json_to_xml(value, line_padding + " "))
result_list.append(f"{line_padding}</{key}>")
elif isinstance(json_obj, list):
for element in json_obj:
result_list.append(json_to_xml(element, line_padding))
else:
result_list.append(f"{line_padding}{json_obj}")

return "\n".join(result_list)


def save_xml_file(xml_str, output_file):
"""
Save the XML string to a file.
"""
with open(output_file, "w") as file:
file.write(xml_str)


def main():
"""
Main function to convert a JSON file to an XML file.
"""
# Input JSON file
input_json_file = "test-input.json"
# Output XML file
output_xml_file = "test-output.xml"

try:
# Load JSON data from a file
with open(input_json_file, "r") as json_file:
json_data = json.load(json_file)

# Convert JSON to XML
xml_data = json_to_xml(json_data)

# Add XML header
xml_data_with_header = (
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xml_data
)

# Save to XML file
save_xml_file(xml_data_with_header, output_xml_file)
print(f"XML file saved successfully to {output_xml_file}")

except Exception as e:
print(f"Error: {e}")


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions json_to_xml/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
jsonschema==4.19.0 # Optional for JSON schema validation (if needed)
8 changes: 8 additions & 0 deletions json_to_xml/test-input.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"note": {
"to": "John",
"from": "Jane",
"heading": "Reminder",
"body": "Don't forget the meeting at 3 PM!"
}
}

0 comments on commit 54f41dc

Please sign in to comment.