Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix/199 attr escape #222

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions json2xml/dicttoxml.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import numbers
from collections.abc import Callable, Sequence
from random import SystemRandom
from typing import Any, Dict, Union
from typing import Any, Union

from defusedxml.minidom import parseString

Expand Down Expand Up @@ -127,7 +127,7 @@
Returns:
str: The string of XML attributes.
"""
attrstring = " ".join([f'{k}="{v}"' for k, v in attr.items()])
attrstring = " ".join([f'{k}="{escape_xml(v)}"' for k, v in attr.items()])
return f'{" " if attrstring != "" else ""}{attrstring}'


Expand Down Expand Up @@ -272,7 +272,7 @@
if isinstance(rawitem, str):
subtree = escape_xml(rawitem)
else:
subtree = rawitem

Check failure on line 275 in json2xml/dicttoxml.py

View workflow job for this annotation

GitHub Actions / mypy

Incompatible types in assignment (expression has type "Any | dict[str, Any]", variable has type "str")

Check failure on line 275 in json2xml/dicttoxml.py

View workflow job for this annotation

GitHub Actions / mypy

Incompatible types in assignment (expression has type "Any | dict[str, Any]", variable has type "str")
else:
# we can not use convert_dict, because rawitem could be non-dict
subtree = convert(
Expand Down
2 changes: 1 addition & 1 deletion json2xml/json2xml.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from pyexpat import ExpatError
from typing import Any, Dict, Optional
from typing import Any

from defusedxml.minidom import parseString

Expand Down
1 change: 0 additions & 1 deletion json2xml/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""Utility methods for converting XML data to dictionary from various sources."""
import json
from typing import Dict, Optional

import urllib3

Expand Down
66 changes: 50 additions & 16 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,19 +1,53 @@
[tool.ruff]
exclude = [
".env",
".venv",
"**/migrations/**",
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"

[project]
name = "json2xml"
version = "3.21.0"
authors = [
{ name = "Vinit Kumar", email = "[email protected]" },
]
lint.ignore = [
"E501", # line too long
"F403", # 'from module import *' used; unable to detect undefined names
"E701", # multiple statements on one line (colon)
"F401", # module imported but unused
description = "Simple Python Library to convert JSON to XML"
readme = "README.rst"
license = { text = "Apache Software License 2.0" }
requires-python = ">=3.10"
classifiers = [
"Development Status :: 6 - Mature",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Natural Language :: English",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Software Development :: Libraries :: Python Modules",
]
line-length = 119
lint.select = [
"I",
"E",
"F",
"W",
keywords = ["json2xml"]

dependencies = [
"defusedxml>=0.7.1",
"requests>=2.31.0"
]

[project.urls]
Homepage = "https://github.com/vinitkumar/json2xml"
Repository = "https://github.com/vinitkumar/json2xml.git"

[tool.setuptools]
packages = ["json2xml"]
include-package-data = true
zip-safe = false

[tool.pytest.ini_options]
testpaths = ["tests"]
python_files = ["test_*.py"]
addopts = "-ra -q"

[project.optional-dependencies]
test = [
"pytest==7.0.1",
"py==1.11.0"
]
54 changes: 2 additions & 52 deletions setup.py
Original file line number Diff line number Diff line change
@@ -1,53 +1,3 @@
#!/usr/bin/env python
from setuptools import setup

"""The setup script."""

from setuptools import setup, find_packages
from json2xml import __version__

with open("README.rst", encoding="utf-8") as readme_file:
readme = readme_file.read()

with open("HISTORY.rst", encoding="utf-8") as history_file:
history = history_file.read()

with open("requirements.in", encoding="utf-8") as requirements_in:
requirements = [requirements_in.read()]

setup_requirements = []

test_requirements = ["pytest==7.0.1", "py==1.11.0"]

setup(
author="Vinit Kumar",
author_email="[email protected]",
classifiers=[
"Development Status :: 6 - Mature",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Natural Language :: English",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
"Topic :: Software Development :: Libraries :: Python Modules",
],
description="Simple Python Library to convert JSON to XML",
install_requires=requirements,
license="Apache Software License 2.0",
long_description=readme + "\n\n" + history,
long_description_content_type="text/x-rst",
include_package_data=True,
keywords="json2xml",
name="json2xml",
packages=find_packages(include=["json2xml"]),
setup_requires=setup_requirements,
test_suite="tests",
tests_require=test_requirements,
url="https://github.com/vinitkumar/json2xml",
version=__version__,
zip_safe=False,
python_requires=">=3.10",
)
setup()
26 changes: 24 additions & 2 deletions tests/test_json2xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,12 @@
InvalidDataError,
JSONReadError,
StringReadError,
URLReadError,
readfromjson,
readfromstring,
readfromurl,
)



class TestJson2xml:
"""Tests for `json2xml` package."""

Expand Down Expand Up @@ -229,3 +228,26 @@ def test_encoding_without_pretty_print(self) -> None:
xmldata = json2xml.Json2xml(data, pretty=False).to_xml()
if xmldata:
assert b'encoding="UTF-8"' in xmldata

def test_escapes_angle_brackets(self):
json_data = json.dumps({"root": {"@attrs": {"HelpText": "version <here>"}}})
result = json2xml.Json2xml(json_data).to_xml()
assert '"HelpText": "version &lt;here&gt;"' in result

def test_escapes_quotes(self):
json_data = json.dumps({"root": {"@attrs": {"Text": "\"quoted\""}}})
result = json2xml.Json2xml(json_data).to_xml()
assert '"Text": "\\"quoted\\""' in result

def test_escapes_ampersands(self):
json_data = json.dumps({"root": {"@attrs": {"Text": "this & that"}}})
result = json2xml.Json2xml(json_data).to_xml()
assert '"Text": "this &amp; that"' in result

def test_escapes_mixed_special_chars(self):
json_data = json.dumps({"root": {"@attrs": {"Text": "<tag> & \"quote\""}}})
result = json2xml.Json2xml(json_data).to_xml()
assert '"Text": "&lt;tag&gt; &amp; \\"quote\\""' in result



Loading
Loading