Skip to content

Commit 54f41dc

Browse files
authored
Merge pull request #1010 from LindaWang7/main
JSON to XML Converter
2 parents bcdccd5 + 3d918a4 commit 54f41dc

File tree

4 files changed

+111
-0
lines changed

4 files changed

+111
-0
lines changed

json_to_xml/README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# JSON to XML Converter
2+
3+
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.
4+
5+
## Features
6+
7+
- Reads JSON data from a file.
8+
- Converts nested JSON objects and arrays into XML elements.
9+
- Outputs well-structured XML files with proper formatting and indentation.
10+
- Adds a standard XML declaration header (`<?xml version="1.0" encoding="UTF-8"?>`).
11+
12+
## Setup Instructions
13+
14+
### Prerequisites
15+
- Python 3.6 or later installed on your system.
16+
17+
### Installation
18+
1. Clone or download this script to your local system.
19+
2. Save the JSON data you want to convert in a file named `input.json` in the same directory as the script.
20+
21+
### Running the Script
22+
1. Open a terminal or command prompt.
23+
2. Navigate to the directory containing the script.
24+
3. Run the script using the following command:
25+
```bash
26+
python json_to_xml.py
27+
The script will generate an XML file named output.xml in the same directory.
28+
29+
## Output
30+
31+
Display images/gifs/videos of output/result of your script so that users can visualize it
32+
33+
## Author(s)
34+
35+
LindaWang7
36+
37+
## Disclaimers, if any
38+
39+
N/A

json_to_xml/json_to_xml.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import json
2+
3+
4+
def json_to_xml(json_obj, line_padding=""):
5+
"""
6+
Convert a JSON object to an XML string.
7+
"""
8+
result_list = []
9+
10+
if isinstance(json_obj, dict):
11+
for key, value in json_obj.items():
12+
result_list.append(f"{line_padding}<{key}>")
13+
result_list.append(json_to_xml(value, line_padding + " "))
14+
result_list.append(f"{line_padding}</{key}>")
15+
elif isinstance(json_obj, list):
16+
for element in json_obj:
17+
result_list.append(json_to_xml(element, line_padding))
18+
else:
19+
result_list.append(f"{line_padding}{json_obj}")
20+
21+
return "\n".join(result_list)
22+
23+
24+
def save_xml_file(xml_str, output_file):
25+
"""
26+
Save the XML string to a file.
27+
"""
28+
with open(output_file, "w") as file:
29+
file.write(xml_str)
30+
31+
32+
def main():
33+
"""
34+
Main function to convert a JSON file to an XML file.
35+
"""
36+
# Input JSON file
37+
input_json_file = "test-input.json"
38+
# Output XML file
39+
output_xml_file = "test-output.xml"
40+
41+
try:
42+
# Load JSON data from a file
43+
with open(input_json_file, "r") as json_file:
44+
json_data = json.load(json_file)
45+
46+
# Convert JSON to XML
47+
xml_data = json_to_xml(json_data)
48+
49+
# Add XML header
50+
xml_data_with_header = (
51+
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" + xml_data
52+
)
53+
54+
# Save to XML file
55+
save_xml_file(xml_data_with_header, output_xml_file)
56+
print(f"XML file saved successfully to {output_xml_file}")
57+
58+
except Exception as e:
59+
print(f"Error: {e}")
60+
61+
62+
if __name__ == "__main__":
63+
main()

json_to_xml/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
jsonschema==4.19.0 # Optional for JSON schema validation (if needed)

json_to_xml/test-input.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"note": {
3+
"to": "John",
4+
"from": "Jane",
5+
"heading": "Reminder",
6+
"body": "Don't forget the meeting at 3 PM!"
7+
}
8+
}

0 commit comments

Comments
 (0)