Git Product home page Git Product logo

json2xml's Introduction

Hi there 👋

I'm a Staff Engineer at KidsKonnect Websites And Onboarding Team and a Core Developer for Django CMS.

I have expertise in Python, C, Go, Node.js/JavaScript, PHP, TypeScript, and databases like Postgres, SQL Server, Redis, SQLite, MongoDB, and Elasticsearch.

I'm skilled in cloud deployments across AWS, Google Cloud, DigitalOcean, and Heroku, and specialize in crafting captivating user interfaces using Tailwind and JavaScript.

Contact Information:

You can find my OSS work here:

  1. 🚀 Published release Final release in SocialSchools/djangocms-admin-style
  2. 💪 Opened PR #344 in vinitkumar/node-twitter
  3. ❌ Closed PR #7686 in django-cms/django-cms
  4. 🎉 Merged PR #298 in vinitkumar/googlecl
  5. 🚀 Published release Style fixes for admin in SocialSchools/djangocms-admin-style

json2xml's People

Contributors

davidthewatson avatar deepsourcebot avatar dependabot[bot] avatar dirkrichter avatar jgroom33 avatar keirospl avatar lgtm-com[bot] avatar ozialien avatar psi29a avatar vinitkumar avatar xel-maker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

json2xml's Issues

dicttoxml adds 'b...'

Describe the bug
Using the function json2xml.dicttoxml.dicttoxml

To Reproduce
Steps to reproduce the behavior:

  1. Run :
from json2xml.dicttoxml import dicttoxml
obj = {'bike': 'blue'}
xml = dicttoxml(obj=obj ,root=False)
print(xml)
  1. See:
b'<bike type="str">blue</bike>'

Expected behavior

<bike type="str">blue</bike>

Screenshots
NA

Desktop (please complete the following information):

  • OS: [macOS]
  • Python 3.9.12
  • json2xml 3.18.0

Additional context
It seems to happen around here:

# dicttoxml.py
# line 445
    if root:
        output.append('<?xml version="1.0" encoding="UTF-8" ?>')
        output_elem = convert(
            obj, ids, attr_type, item_func, cdata, item_wrap, parent=custom_root
        )
        output.append(f"<{custom_root}{namespacestr}>{output_elem}</{custom_root}>")
    else:
-->     output.append( #adds ' '
            convert(obj, ids, attr_type, item_func, cdata, item_wrap, parent="")
        )

--> return "".join(output).encode("utf-8") #adds b 

3.15.1 running test yields warning

Describe the bug
To start contributing, I have run the test after cloning the repo locally.

To Reproduce
Steps to reproduce the behavior:
Clone 3.15.1
Run test

Expected behavior
All tests should pass flawlessly.

Screenshots
N/A

Desktop (please complete the following information):
MacOS

Additional context
In order to start adding features, I would suggest fixing all the warnings, so there is confidence about any future addition.

I think I have time to propose a PR with fixes soon

json with multiple records generates invalid XML

A json file with multiple entries is creating an invalid file:

{"records":[{"val1": "test","val2":"test"},{"val1": "test2","val2":"test2"}]}

It creates two records tag not belonging to any other tag.

When printing straight from dict2xml, it is possible to use the flag "wrap=all" to handle cases like this (You can also pass an argument to prettify and get rid of Beautifulsoap)

Attr Type Remove

Hello
I tried to convert JSON into XML and it's work fine but it comes with type="str". is there any way to ignore this attribute?

Omit <item>...</item> from arrays

Assume the following json:

{"my_items":[{"my_item":{"id":1} },{"my_item":{"id":2} }]}

Current behavior:

    <all>
      <my_items type="list">
        <item>
          <my_item>
              <id type="int">1</id>
          </my_item>
        </item>
        <item>
          <my_item>
              <id type="int">2</id>
          </my_item>
        </item>
      </list>
    </all>

Desired behavior:

Add attribute item_wrap as Boolean

    data = readfromstring(
        '{"my_items":[{"my_item":{"id":1} },{"my_item":{"id":2} }]}'
    )
    print(json2xml.Json2xml(data, item_wrap=False).to_xml())
    <all>
      <my_items type="list">
        <my_item>
            <id type="int">1</id>
        </my_item>
        <my_item>
            <id type="int">2</id>
        </my_item>
      </list>
    </all>

Calls to `convert_*` have misaligned arguments

Describe the bug
In the convert() function in dicttoxml.py, there are several calls to convert_* functions that use positional arguments that are getting sent to the wrong parameters.

For example,

return convert_kv(item_name, obj, attr_type, cdata)

makes a call to convert_kv(), but the signature of that function has the cdata parameter after the attr parameter, so the two get mixed up on the call:
def convert_kv(key, val, attr_type, attr={}, cdata: bool = False):

I think if these calls were switched to use keyword parameters, this bug would be fixed very quickly. Presently, though, it's causing things to fail for me.

To Reproduce
Running the following in a Python console shows the error I'm seeing:

from json import dumps
from json2xml.json2xml import Json2xml
input_dict = {'response': {'results': {'user': [{'name': 'Ezequiel', 'age': '33', 'city': 'San Isidro'}, {'name': 'Belén', 'age': '30', 'city': 'San Isidro'}]}}}
Json2xml(dumps(input_dict), wrapper='response', pretty=False, attr_type=False, item_wrap=False).to_xml()

The resulting AttributeError: 'bool' object has no attribute 'items' error is a result of attr being set to False instead of its default value of an empty dict {}.

Library ends program execution upon error instead of throwing exception

Describe the bug
When the code in utils.py encounters an error it just stops the program execution instead of throwing an exception or printing an error like standard libraries do.

To Reproduce
Steps to reproduce the behavior:

  1. Pass an invalid or incorrectly formatted JSON file to any function in utils.py (e.g. readfromstring, readfromjson)
  2. The program will stop running completely.=

Expected behavior
When an error or exception is encountered, throw an exception for the caller to catch instead of exiting the program.

Desktop (please complete the following information):
N/A - irrelevant

Typo in import statement?

The import statement now reads:

from src.json2xml import Json2xml

After installing, I had to change to:

from json2xml.json2xml import Json2xml

In order for the script to work. Can you confirm?

Pip3 Error for python3.5

I get the following error after I attempt to pip3 install json2xml

pip3 install json2xml
Collecting json2xml
Using cached json2xml-2.2.0.tar.gz
Requirement already satisfied: dict2xml==1.5 in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (from json2xml)
Collecting six==1.11.0 (from json2xml)
Using cached six-1.11.0-py2.py3-none-any.whl
Collecting requests==2.18.4 (from json2xml)
Using cached requests-2.18.4-py2.py3-none-any.whl
Requirement already satisfied: xmltodict==0.11.0 in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (from json2xml)
Collecting urllib3<1.23,>=1.21.1 (from requests==2.18.4->json2xml)
Using cached urllib3-1.22-py2.py3-none-any.whl
Collecting chardet<3.1.0,>=3.0.2 (from requests==2.18.4->json2xml)
Using cached chardet-3.0.4-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests==2.18.4->json2xml)
Using cached certifi-2017.11.5-py2.py3-none-any.whl
Collecting idna<2.7,>=2.5 (from requests==2.18.4->json2xml)
Using cached idna-2.6-py2.py3-none-any.whl
Installing collected packages: six, urllib3, chardet, certifi, idna, requests, json2xml
Found existing installation: six 1.10.0
Uninstalling six-1.10.0:
Successfully uninstalled six-1.10.0
Rolling back uninstall of six
Exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 2807, in _dep_map
return self.__dep_map
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 2618, in getattr
raise AttributeError(attr)
AttributeError: _DistInfoDistribution__dep_map

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 2798, in _parsed_pkg_info
return self._pkg_info
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 2618, in getattr
raise AttributeError(attr)
AttributeError: _pkg_info

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip-9.0.1-py3.5.egg/pip/basecommand.py", line 215, in main
status = self.run(options, args)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip-9.0.1-py3.5.egg/pip/commands/install.py", line 342, in run
prefix=options.prefix_path,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip-9.0.1-py3.5.egg/pip/req/req_set.py", line 784, in install
**kwargs
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip-9.0.1-py3.5.egg/pip/req/req_install.py", line 851, in install
self.move_wheel_files(self.source_dir, root=root, prefix=prefix)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip-9.0.1-py3.5.egg/pip/req/req_install.py", line 1064, in move_wheel_files
isolated=self.isolated,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip-9.0.1-py3.5.egg/pip/wheel.py", line 247, in move_wheel_files
prefix=prefix,
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pip-9.0.1-py3.5.egg/pip/locations.py", line 140, in distutils_scheme
d = Distribution(dist_args)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/setuptools/dist.py", line 320, in init
_Distribution.init(self, attrs)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/distutils/dist.py", line 281, in init
self.finalize_options()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/setuptools/dist.py", line 386, in finalize_options
ep.require(installer=self.fetch_build_egg)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 2318, in require
items = working_set.resolve(reqs, env, installer, extras=self.extras)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 862, in resolve
new_requirements = dist.requires(req.extras)[::-1]
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 2562, in requires
dm = self._dep_map
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 2809, in _dep_map
self.__dep_map = self._compute_dependencies()
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 2818, in _compute_dependencies
for req in self._parsed_pkg_info.get_all('Requires-Dist') or []:
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 2800, in _parsed_pkg_info
metadata = self.get_metadata(self.PKG_INFO)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 1468, in get_metadata
value = self._get(self._fn(self.egg_info, name))
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/pkg_resources/init.py", line 1577, in _get
with open(path, 'rb') as stream:
FileNotFoundError: [Errno 2] No such file or directory: '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/six-1.10.0.dist-info/METADATA'

PyTest pegged to version number

PyTest is currently pegged against 7.0.0rc1

Since other projects make use of poetry, poetry is very strict about handling deps.

Can you set PyTest not to be a dependancy?

It's perfectly fine for testing, but not for a release to production kind of thing.

[Uncaught exception] UnicodeDecodeError when calling to_xml with arbitrary data

Describe the bug
I found out that theJson2xml(data).to_xml() method can raise a UnicodeDecodeError leading to a crash of the running program.

This could be problematic if users of the library are dealing with untrusted data since this issue will lead to a DoS. This should be detected and an execption should be triggered

To Reproduce
Steps to reproduce the behavior:
image

Expected behavior
This execption should be expected.

Failed building wheel for json2xml

pip3 install json2xml

Collecting json2xml
Downloading https://files.pythonhosted.org/packages/45/a6/65509927c74eff40f001e7ab3e830849545cc8f41cc6111f1bc11c282391/json2xml-2.2.0.tar.gz
Collecting dict2xml==1.5 (from json2xml)
Downloading https://files.pythonhosted.org/packages/7e/c7/728fe5b79783b2c44af4381820dd6cbfddf7ee2a27b79023b623fe189357/dict2xml-1.5.tar.gz
Requirement already satisfied: six==1.11.0 in /home/hemanth/anaconda3/lib/python3.6/site-packages (from json2xml) (1.11.0)
Requirement already satisfied: requests==2.18.4 in /home/hemanth/anaconda3/lib/python3.6/site-packages (from json2xml) (2.18.4)
Collecting xmltodict==0.11.0 (from json2xml)
Downloading https://files.pythonhosted.org/packages/42/a9/7e99652c6bc619d19d58cdd8c47560730eb5825d43a7e25db2e1d776ceb7/xmltodict-0.11.0-py2.py3-none-any.whl
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /home/hemanth/anaconda3/lib/python3.6/site-packages (from requests==2.18.4->json2xml) (3.0.4)
Requirement already satisfied: idna<2.7,>=2.5 in /home/hemanth/anaconda3/lib/python3.6/site-packages (from requests==2.18.4->json2xml) (2.6)
Requirement already satisfied: urllib3<1.23,>=1.21.1 in /home/hemanth/anaconda3/lib/python3.6/site-packages (from requests==2.18.4->json2xml) (1.22)
Requirement already satisfied: certifi>=2017.4.17 in /home/hemanth/anaconda3/lib/python3.6/site-packages (from requests==2.18.4->json2xml) (2017.7.27.1)
Building wheels for collected packages: json2xml, dict2xml
Running setup.py bdist_wheel for json2xml ... error
Complete output from command /home/hemanth/anaconda3/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-install-sjea2obu/json2xml/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" bdist_wheel -d /tmp/pip-wheel-svy2m8ib --python-tag cp36:
running bdist_wheel
running build
running build_py
creating build
creating build/lib
creating build/lib/src
copying src/json2xml.py -> build/lib/src
copying src/init.py -> build/lib/src
copying src/cli.py -> build/lib/src
running egg_info
writing json2xml.egg-info/PKG-INFO
writing dependency_links to json2xml.egg-info/dependency_links.txt
writing requirements to json2xml.egg-info/requires.txt
writing top-level names to json2xml.egg-info/top_level.txt
reading manifest file 'json2xml.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
writing manifest file 'json2xml.egg-info/SOURCES.txt'
installing to build/bdist.linux-x86_64/wheel
running install
running install_lib
creating build/bdist.linux-x86_64
creating build/bdist.linux-x86_64/wheel
creating build/bdist.linux-x86_64/wheel/src
copying build/lib/src/json2xml.py -> build/bdist.linux-x86_64/wheel/src
copying build/lib/src/init.py -> build/bdist.linux-x86_64/wheel/src
copying build/lib/src/cli.py -> build/bdist.linux-x86_64/wheel/src
running install_egg_info
Copying json2xml.egg-info to build/bdist.linux-x86_64/wheel/json2xml-2.2.0-py3.6.egg-info
running install_scripts
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-install-sjea2obu/json2xml/setup.py", line 19, in
'xmltodict==0.11.0'
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/init.py", line 129, in setup
return distutils.core.setup(**attrs)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/core.py", line 148, in setup
dist.run_commands()
File "/home/hemanth/anaconda3/lib/python3.6/distutils/dist.py", line 955, in run_commands
self.run_command(cmd)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/wheel/bdist_wheel.py", line 215, in run
self.run_command('install')
File "/home/hemanth/anaconda3/lib/python3.6/distutils/cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/command/install.py", line 61, in run
return orig.install.run(self)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/command/install.py", line 557, in run
self.run_command(cmd_name)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/command/install_scripts.py", line 17, in run
import setuptools.command.easy_install as ei
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 52, in
from setuptools.package_index import (
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/package_index.py", line 31, in
from setuptools.wheel import Wheel
ModuleNotFoundError: No module named 'setuptools.wheel'


Failed building wheel for json2xml
Running setup.py clean for json2xml
Running setup.py bdist_wheel for dict2xml ... error
Complete output from command /home/hemanth/anaconda3/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-install-sjea2obu/dict2xml/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" bdist_wheel -d /tmp/pip-wheel-i499ukwb --python-tag cp36:
running bdist_wheel
running build
running build_py
creating build
creating build/lib
creating build/lib/dict2xml
copying dict2xml/logic.py -> build/lib/dict2xml
copying dict2xml/init.py -> build/lib/dict2xml
installing to build/bdist.linux-x86_64/wheel
running install
running install_lib
creating build/bdist.linux-x86_64
creating build/bdist.linux-x86_64/wheel
creating build/bdist.linux-x86_64/wheel/dict2xml
copying build/lib/dict2xml/logic.py -> build/bdist.linux-x86_64/wheel/dict2xml
copying build/lib/dict2xml/init.py -> build/bdist.linux-x86_64/wheel/dict2xml
running install_egg_info
running egg_info
writing dict2xml.egg-info/PKG-INFO
writing dependency_links to dict2xml.egg-info/dependency_links.txt
writing requirements to dict2xml.egg-info/requires.txt
writing top-level names to dict2xml.egg-info/top_level.txt
reading manifest file 'dict2xml.egg-info/SOURCES.txt'
writing manifest file 'dict2xml.egg-info/SOURCES.txt'
Copying dict2xml.egg-info to build/bdist.linux-x86_64/wheel/dict2xml-1.5-py3.6.egg-info
running install_scripts
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-install-sjea2obu/dict2xml/setup.py", line 25, in
, license = "WTFPL"
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/init.py", line 129, in setup
return distutils.core.setup(**attrs)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/core.py", line 148, in setup
dist.run_commands()
File "/home/hemanth/anaconda3/lib/python3.6/distutils/dist.py", line 955, in run_commands
self.run_command(cmd)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/wheel/bdist_wheel.py", line 215, in run
self.run_command('install')
File "/home/hemanth/anaconda3/lib/python3.6/distutils/cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/command/install.py", line 61, in run
return orig.install.run(self)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/command/install.py", line 557, in run
self.run_command(cmd_name)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/command/install_scripts.py", line 17, in run
import setuptools.command.easy_install as ei
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 52, in
from setuptools.package_index import (
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/package_index.py", line 31, in
from setuptools.wheel import Wheel
ModuleNotFoundError: No module named 'setuptools.wheel'


Failed building wheel for dict2xml
Running setup.py clean for dict2xml
Failed to build json2xml dict2xml
Installing collected packages: dict2xml, xmltodict, json2xml
Running setup.py install for dict2xml ... error
Complete output from command /home/hemanth/anaconda3/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-install-sjea2obu/dict2xml/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-record-rxc6csoh/install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
creating build
creating build/lib
creating build/lib/dict2xml
copying dict2xml/logic.py -> build/lib/dict2xml
copying dict2xml/init.py -> build/lib/dict2xml
running install_lib
creating /home/hemanth/anaconda3/lib/python3.6/site-packages/dict2xml
copying build/lib/dict2xml/logic.py -> /home/hemanth/anaconda3/lib/python3.6/site-packages/dict2xml
copying build/lib/dict2xml/init.py -> /home/hemanth/anaconda3/lib/python3.6/site-packages/dict2xml
byte-compiling /home/hemanth/anaconda3/lib/python3.6/site-packages/dict2xml/logic.py to logic.cpython-36.pyc
byte-compiling /home/hemanth/anaconda3/lib/python3.6/site-packages/dict2xml/init.py to init.cpython-36.pyc
running install_egg_info
running egg_info
writing dict2xml.egg-info/PKG-INFO
writing dependency_links to dict2xml.egg-info/dependency_links.txt
writing requirements to dict2xml.egg-info/requires.txt
writing top-level names to dict2xml.egg-info/top_level.txt
reading manifest file 'dict2xml.egg-info/SOURCES.txt'
writing manifest file 'dict2xml.egg-info/SOURCES.txt'
Copying dict2xml.egg-info to /home/hemanth/anaconda3/lib/python3.6/site-packages/dict2xml-1.5-py3.6.egg-info
running install_scripts
Traceback (most recent call last):
File "", line 1, in
File "/tmp/pip-install-sjea2obu/dict2xml/setup.py", line 25, in
, license = "WTFPL"
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/init.py", line 129, in setup
return distutils.core.setup(**attrs)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/core.py", line 148, in setup
dist.run_commands()
File "/home/hemanth/anaconda3/lib/python3.6/distutils/dist.py", line 955, in run_commands
self.run_command(cmd)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/command/install.py", line 61, in run
return orig.install.run(self)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/command/install.py", line 557, in run
self.run_command(cmd_name)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "/home/hemanth/anaconda3/lib/python3.6/distutils/dist.py", line 974, in run_command
cmd_obj.run()
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/command/install_scripts.py", line 17, in run
import setuptools.command.easy_install as ei
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/command/easy_install.py", line 52, in
from setuptools.package_index import (
File "/home/hemanth/anaconda3/lib/python3.6/site-packages/setuptools/package_index.py", line 31, in
from setuptools.wheel import Wheel
ModuleNotFoundError: No module named 'setuptools.wheel'

----------------------------------------

Command "/home/hemanth/anaconda3/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-install-sjea2obu/dict2xml/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" install --record /tmp/pip-record-rxc6csoh/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-install-sjea2obu/dict2xml/

item_wrap for str and int

item_wrap=False currently only supports list of dict

It should also support list of str and int

Input:

{"my_str_items":["a","b"]}

item_wrap=False output:

<all>
  <my_str_items type="list">
    <item type="str">a</item>
    <item type="str">b</item>
  </my_str_items>
</all>

item_wrap=True output:

<all>
  <my_str_items>a</my_str_items>
  <my_str_items>b</my_str_items>
</all>

Support for Python3.10

Running the test suite with Python3.10b1,resulted in these warnings:

test_read_from_url (tests.test_json2xml.TestJson2xml) ... /opt/hostedtoolcache/Python/3.10.0-beta.1/x64/lib/python3.10/site-packages/urllib3/util/ssl_.py:281: DeprecationWarning: ssl module: PROTOCOL_TLS is deprecated
34
  context = SSLContext(ssl_version or PROTOCOL_TLS)
35
/opt/hostedtoolcache/Python/3.10.0-beta.1/x64/lib/python3.10/site-packages/urllib3/connection.py:512: DeprecationWarning: ssl module: match_hostname() is deprecated
36
  match_hostname(cert, asserted_hostname)
37
ok
38
test_read_from_wrong_url (tests.test_json2xml.TestJson2xml) ... ok

Let's look into this and find a backward compatible way to fix these warnings.

Installed but doesn't work.

[root ~]# python -m json2xml.cli ./test.json
/usr/bin/python: No module named json2xml.cli

[root ~]# pip show json2xml

Metadata-Version: 1.0
Name: json2xml
Version: 1.1.0
Summary: To covert json data to xml data
Home-page: http://github.com:vinitkumar/json2xml.git
Author: Vinit Kumar
Author-email: [email protected]
License: UNKNOWN
Location: /usr/lib/python2.7/site-packages
Requires: BeautifulSoup4, dict2xml, simplejson, six, requests
Classifiers:

What's wrong?

pip installed version of json2xml doesn't include to_xml() nor Json2xml class

$ pip list | grep json
json2xml                  3.0.1     
jsonschema                2.6.0  

$ python
...
>>> import json2xml
>>> dir(json2xml)
['__author__', '__builtins__', '__cached__', '__doc__', '__email__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__', '__version__', 'readfromjson', 'readfromstring', 'readfromurl', 'utils']
>>> json2xml.__version__
'3.0.0'     
>>>exit()

$ pip install --upgrade json2xml
Requirement already up-to-date: json2xml in /Users/sinjihn/VirtualEnvironments/python3_venv/lib/python3.7/site-packages (3.0.1)

Looks like the version of json2xml that gets installed via pip is an older version or missing something?

Python 3 support

$ sudo python3.4 setup.py install
running install
running bdist_egg
running egg_info
writing pbr to json2xml.egg-info/pbr.json
writing requirements to json2xml.egg-info/requires.txt
writing json2xml.egg-info/PKG-INFO
writing top-level names to json2xml.egg-info/top_level.txt
writing dependency_links to json2xml.egg-info/dependency_links.txt
reading manifest file 'json2xml.egg-info/SOURCES.txt'
reading manifest template 'MANIFEST.in'
warning: no files found matching 'history.md'
writing manifest file 'json2xml.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
creating build/bdist.linux-x86_64
creating build/bdist.linux-x86_64/egg
creating build/bdist.linux-x86_64/egg/json2xml
copying build/lib/json2xml/json2xml.py -> build/bdist.linux-x86_64/egg/json2xml
copying build/lib/json2xml/__init__.py -> build/bdist.linux-x86_64/egg/json2xml
byte-compiling build/bdist.linux-x86_64/egg/json2xml/json2xml.py to json2xml.cpython-34.pyc
  File "build/bdist.linux-x86_64/egg/json2xml/json2xml.py", line 33
    print "I/O error({0}): {1}".format(e.errno, e.strerror)
                              ^
SyntaxError: invalid syntax
...
Processing dependencies for json2xml==1.0.1
Searching for wsgiref==0.1.2
Reading https://pypi.python.org/simple/wsgiref/
Best match: wsgiref 0.1.2
Downloading https://pypi.python.org/packages/source/w/wsgiref/wsgiref-0.1.2.zip#md5=29b146e6ebd0f9fb119fe321f7bcf6cb
Processing wsgiref-0.1.2.zip
Writing /tmp/easy_install-15t7k6i3/wsgiref-0.1.2/setup.cfg
Running wsgiref-0.1.2/setup.py -q bdist_egg --dist-dir /tmp/easy_install-15t7k6i3/wsgiref-0.1.2/egg-dist-tmp-3y_lk_nn
Traceback (most recent call last):
  File "/usr/lib/python3.4/site-packages/setuptools/sandbox.py", line 154, in save_modules
    yield saved
  File "/usr/lib/python3.4/site-packages/setuptools/sandbox.py", line 195, in setup_context
    yield
  File "/usr/lib/python3.4/site-packages/setuptools/sandbox.py", line 239, in run_setup
    DirectorySandbox(setup_dir).run(runner)
  File "/usr/lib/python3.4/site-packages/setuptools/sandbox.py", line 269, in run
    return func()
  File "/usr/lib/python3.4/site-packages/setuptools/sandbox.py", line 238, in runner
    _execfile(setup_script, ns)
  File "/usr/lib/python3.4/site-packages/setuptools/sandbox.py", line 46, in _execfile
    exec(code, globals, locals)
  File "/tmp/easy_install-15t7k6i3/wsgiref-0.1.2/setup.py", line 5, in <module>

  File "/tmp/easy_install-15t7k6i3/wsgiref-0.1.2/ez_setup/__init__.py", line 170
    print "Setuptools version",version,"or greater has been installed."
                             ^
SyntaxError: Missing parentheses in call to 'print'
...

ImportError: cannot import name 'json2xml'

Hi Vinit,

I just installed the latest version with your upgrade command. My python script is saying ImportError: cannot import name 'json2xml'. What do I need to do? i googled but didn't find anything. thanks!

writing to XML file

Hi,

I am pretty close to using your tool to do what I need. The last issue I am having is I can't get the final out put to export to and XML File. I see the result in the output window but it won't save to file and the code just seems to end after running data = Json2xml.fromurl(result).data. Nothing happens after I get here 2.

import urllib.request as urlreq
import urllib.parse as urlparse
#import json
from src.json2xml import Json2xml

inPts = {"geometryType" : "esriGeometryPoint",
         "spatialReference" : {"wkid" : 54003},
         'features':[{'geometry':{'x': -13308192.1956127,'y':  4221903.58555983}}]}

dist = {'distance':8.5,'units':'esriMiles'}

data = {'Input_Observation_Point': inPts,
        'Viewshed_Distance': dist,
        'f': 'pjson'}

params = urlparse.urlencode(data)
params = params.encode('ascii') #('utf-8')

URL  = 'http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/Elevation/ESRI_Elevation_World/GPServer/Viewshed/execute'

XMLFILE = open("M:\Temp\XML.txt","w")
JSONFILE = open("M:\Temp\JSON.txt","w")

print ("I got here 1")
result = urlreq.urlopen(URL, params).read()
#print (result)
JSONFILE.write(str(result))

print ("I got here 2")
data = Json2xml.fromurl(result).data
print ("I got here 3")
data_object2 = Json2xml(data)
print ("I got here 4")
data_object2.json2xml() #xml output
print ("I got here 4")
#print (data_object2.json2xml())

XMLFILE.write(data_object2)

XMLFILE.close()
JSONFILE.close()

print ("I got here 5")

Do you have any thoughts I have included my code? The goal is to put the output into an XMLFile

Thanks,
Matt

Getting an error while using pretty keyword

hi,

i am receiving an error "TypeError: init() got an unexpected keyword argument 'pretty'"

Details below:

>>> print(json2xml.Json2xml(output, wrapper="result", pretty=True).to_xml())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __init__() got an unexpected keyword argument 'pretty'

I am using python 3.7.0.

ImportError: No module named 'src'

user@amd-e-450:$ python3 -V
Python 3.5.2
user@amd-e-450:
$ pip3 install json2xml
Collecting json2xml
Downloading json2xml-1.1.0.tar.gz
Collecting BeautifulSoup4==4.4.1 (from json2xml)
Downloading beautifulsoup4-4.4.1-py3-none-any.whl (81kB)
100% |████████████████████████████████| 81kB 410kB/s
Collecting dict2xml==1.3 (from json2xml)
Downloading dict2xml-1.3.tar.gz
Collecting simplejson==3.6.5 (from json2xml)
Downloading simplejson-3.6.5.tar.gz (73kB)
100% |████████████████████████████████| 81kB 684kB/s
Collecting six==1.9.0 (from json2xml)
Downloading six-1.9.0-py2.py3-none-any.whl
Collecting requests==2.9.1 (from json2xml)
Downloading requests-2.9.1-py2.py3-none-any.whl (501kB)
100% |████████████████████████████████| 501kB 477kB/s
Building wheels for collected packages: json2xml, dict2xml, simplejson
Running setup.py bdist_wheel for json2xml ... done
Stored in directory: /home/user/.cache/pip/wheels/4e/5e/51/252d1138579cf48debd311667fa57b25b0ff50177447e1906b
Running setup.py bdist_wheel for dict2xml ... done
Stored in directory: /home/user/.cache/pip/wheels/e6/3e/13/d3f21cf1b95a03d8d940813562b85a3a1e173774ca226c63c4
Running setup.py bdist_wheel for simplejson ... done
Stored in directory: /home/user/.cache/pip/wheels/81/9e/4e/c7a8c0ce2d1e19874582fd21ae83eecf21d826582a54729394
Successfully built json2xml dict2xml simplejson
Installing collected packages: BeautifulSoup4, six, dict2xml, simplejson, requests, json2xml
Successfully installed BeautifulSoup4-4.4.1 dict2xml-1.3 json2xml-1.1.0 requests-2.9.1 simplejson-3.6.5 six-1.9.0
You are using pip version 8.1.1, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
user@amd-e-450:$ vi 1.py
user@amd-e-450:
$ mc

user@amd-e-450:$
user@amd-e-450:
$ python3 1.py
Traceback (most recent call last):
File "1.py", line 1, in
from src.json2xml import Json2xml
ImportError: No module named 'src'

user@amd-e-450:~$ cat 1.py
from src.json2xml import Json2xml
data = Json2xml.fromjsonfile('examples/example.json').data
data_object = Json2xml(data)
data_object.json2xml() #xml output

Changed file:
user@amd-e-450:~$ python3 1.py
Traceback (most recent call last):
File "1.py", line 1, in
from json2xml import Json2xml
ImportError: cannot import name 'Json2xml'

user@amd-e-450:~$ cat 1.py
from json2xml import Json2xml
data = Json2xml.fromjsonfile('examples/example.json').data
data_object = Json2xml(data)
data_object.json2xml() #xml output

json2xml should support adding namespaces

Is your feature request related to a problem? Please describe.
Today json2xml does not allow you to read the namespaces as created from xml2dict

Describe the solution you'd like
I would like to see namespaces also part of xml tags

Describe alternatives you've considered
Adding namespaces manually

Additional context
https://pypi.org/project/xmltodict/

Bad Json format

Describe the bug
When trying to read from a json file, that contains a bad json format the library craches the python program

To Reproduce
Steps to reproduce the behavior:

  1. Try to import a bad json file
  2. Use json2xml.utils readfromjson

Expected behavior
I expected that the library raise an exception to be handled in my the python module

64bit Package

Hi is json2xml only a 32bit package or is a 64bit package available

Installation fails

trying to install:
$ pip install -U json2xml
Collecting json2xml
Downloading json2xml-1.0.0.tar.gz
Traceback (most recent call last):
File "", line 20, in
File "/tmp/pip-build-92CsKj/json2xml/setup.py", line 17, in
'requirements.txt')).read().split(),
IOError: [Errno 2] No such file or directory: '/tmp/pip-build-92CsKj/json2xml/requirements.txt'
Complete output from command python setup.py egg_info:
Traceback (most recent call last):

  File "<string>", line 20, in <module>

  File "/tmp/pip-build-92CsKj/json2xml/setup.py", line 17, in <module>

    'requirements.txt')).read().split(),

IOError: [Errno 2] No such file or directory: '/tmp/pip-build-92CsKj/json2xml/requirements.txt'

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-92CsKj/json2xml

Latin characters not being displayed properly.

Describe the bug
Whenever I try to convert a JSON that contains latin characters (for example ç) it returns me "�" instead.

To Reproduce
Just trying to convert a JSON with any latin character (á, à, ç, etc.)

Expected behavior
I expect the output to be (for example) ç not �

Desktop (please complete the following information):

  • OS: Windows 10
  • Version 1909

Additional context
Add any other context about the problem here.

EDIT: VSCode bug, keep going.

json to xml conversion with xml namespace

Hi, i need to convert a json data to xml. the sample code is as below.


from json2xml import json2xml
from json2xml.utils import readfromurl, readfromstring, readfromjson
data = readfromstring(

 '{"ra:covered-product-agreement":{"login":"mojombo","id":1,"avatar_url":"https://avatars0.githubusercontent.com/u/1?v=4"}}'
)
return json2xml.Json2xml(data, attr_type=False).to_xml()

where "ra" is the namespace. but the conversion is not exactly happening.

the result expecting is

<ra:covered-product-agreement>
		<login>mojombo</login>
		<id>1</id>
		<avatar_url>https://avatars0.githubusercontent.com/u/1?v=4</avatar_url>
	</ra:covered-product-agreement>

with current version the result received is

<key name="ra:covered-product-agreement">
		<login>mojombo</login>
		<id>1</id>
		<avatar_url>https://avatars0.githubusercontent.com/u/1?v=4</avatar_url>
	</key>

Please suggest a way to achieve this.

Thanks

BaseExecption

am new in python dev, and i have a problem when converting data from Json

here my error :
exceptions must derive from BaseException

Replace xml.dom with defusedxml

Describe the bug
A clear and concise description of what the bug is.
[Security]

Scanned the package at (Snyk)[https://app.snyk.io/org/vinitkumar/project/39009c4a-8759-4a97-a0c3-dbe224fe99úú]. Seems like
replacing xml.dom usage with defusedxml is an easy and API compatible approach which we can
use to prevent a vector of attacks

xml.dom.minidom.parseString is considered insecure. Use an analog from the defusedxml package.

Multiple nested wrappers

Is your feature request related to a problem? Please describe.
I would like to convert json to xml with multiple nested wrapper
like
<First> <Second> . . </Second> </First>

Describe the solution you'd like
You can provide an option like to accept "," separated values or new subwrapper1 string

Describe alternatives you've considered
No

Additional context

dicttoxml ignores the root param

Code snippit:

from jsontoxml import dicttoxml
payload={'mock': 'payload'}
result = dicttoxml(payload, attr_type=False, root=False)
print(result)

Result:

b'<?xml version="1.0" encoding="UTF-8" ?><root><mock>payload</mock></root>'

What it should look like:

b'<mock>payload</mock>'

TypeError: 'bool' object does not support item assignment

Describe the bug

  File "../Library/Python/3.8/lib/python/site-packages/dicttoxml.py", line 333, in convert_kv
    attr['type'] = get_xml_type(val)
TypeError: 'bool' object does not support item assignment

To Reproduce

 def testJson2XML(self):
        ''' test Json  XML conversion '''
        jsonText='{"count": 1, "events": [{"acronym": "EuroPar 2020", "city": "Warsaw", "country": "Poland", "creation_date": "2020-02-27T14:44:52+00:00", "end_date": "2020-08-28T00:00:00+00:00", "event": "EuroPar 2020", "foundBy": "EuroPar 2020", "homepage": "https://2020.euro-par.org/", "modification_date": "2020-02-27T14:44:52+00:00", "series": "EuroPar", "source": "OPEN RESEARCH", "start_date": "2020-08-24T00:00:00+00:00", "title": "International European Conference on Parallel and Distributed Computing", "url": "https://www.openresearch.org/wiki/EuroPar 2020"}]}'
        xml=json2xml.Json2xml(jsonText).to_xml()  
        print(xml)    

Expected behavior
should not fail

Desktop (please complete the following information):

  • OS: MacOS 10.13.6

remove parameters from end tag

if a tag has parameter like below end tag also has the prameter and tag name and parameter is merged by underscore.

json
'methodName version="1.0"' : 'XXXXXXXXXXXXXXXXXXXXXXX'

xml
<methodName_version_"1.0">XXXXXXXXXXXXXXXXXXXXXXX</methodName_version_1.0>

how can it be like this?
xml
<methodName version="1.0">XXXXXXXXXXXXXXXXXXXXXXX</methodName>

Automatically add id's to xml node for nested JSON arrays

When adding a nested JSON array, automatically add id's to xml nodes

Example JSON file:

[
{
    "publication_number": "EP-0477689-B1",
    "application_number": "EP-91115483-A",
    "country_code": "EP",
    "kind_code": "B1",
    "application_kind": "A",
    "application_number_formatted": "EP19910115483",
    "pct_number": "",
    "family_id": "24344316",
    "title_localized": [
      {
        "text": "Verfahren zur Herstellung eines zur Filtration geeigneten porösen Polysulfon-Mediums",
        "language": "de"
      },
      {
        "text": "Procédé de fabrication d&#39;un milieu poreux en polysulfone approprié à la filtration",
        "language": "fr"
      },
      {
        "text": "Process for the preparation of porous polysulfone media suitable for filtration",
        "language": "en"
      }
    ],
    "inventor": [
      "BEDWELL, WILLIAM B.",
      "YATES, STEPHEN F."
    ],
    "inventor_harmonized": [
      {
        "name": "BEDWELL WILLIAM B",
        "country_code": "US"
      },
      {
        "name": "YATES STEPHEN F",
        "country_code": "US"
      }
    ],
    "assignee": [
      "Cpc Engineering Corporation"
    ],
    "assignee_harmonized": [
      {
        "name": "CPC ENG CORP",
        "country_code": "US"
      }
    ],
    "entity_status": "",
    "art_unit": ""
  },
  {
    "publication_number": "EP-2309181-B1",
    "application_number": "EP-10012345-A",
    "country_code": "EP",
    "kind_code": "B1",
    "application_kind": "A",
    "application_number_formatted": "EP20100012345",
    "pct_number": "",
    "family_id": "43332270",
    "title_localized": [
      {
        "text": "Installation de chaudière à combustion à oxy-fuel et son procédé de fonctionnement",
        "language": "fr"
      },
      {
        "text": "Oxyfuel combustion boiler plant and operation method of oxyfuel combustion boiler plant",
        "language": "en"
      },
      {
        "text": "Oxyfuel-Brennkessel und Betriebsverfahren dafür",
        "language": "de"
      }
    ],
    "inventor": [
      "TANIGUCHI, MASAYUKI",
      "SHIBATA, TSUYOSHI",
      "HAYASHI, YOSHIHARU"
    ],
    "inventor_harmonized": [
      {
        "name": "TANIGUCHI MASAYUKI",
        "country_code": "JP"
      },
      {
        "name": "SHIBATA TSUYOSHI",
        "country_code": "JP"
      },
      {
        "name": "HAYASHI YOSHIHARU",
        "country_code": "JP"
      }
    ],
    "assignee": [
      "Mitsubishi Hitachi Power Systems, Ltd."
    ],
    "assignee_harmonized": [
      {
        "name": "MITSUBISHI HITACHI POWER SYS",
        "country_code": "JP"
      }
    ],
    "entity_status": "",
    "art_unit": ""
  }
]

When converting it should automatically add id's to the nodes like below for every json array element:

<?xml version="1.0" encoding="UTF-8" ?>
<root>
  <row id="1">
    <publication_number>EP-0477689-B1</publication_number>
    <application_number>EP-91115483-A</application_number>
    <country_code>EP</country_code>
    <kind_code>B1</kind_code>
    <application_kind>A</application_kind>
    <application_number_formatted>EP19910115483</application_number_formatted>
    <pct_number></pct_number>
    <family_id>24344316</family_id>
    <title_localized>
      <text>Verfahren zur Herstellung eines zur Filtration geeigneten porösen Polysulfon-Mediums</text>
      <language>de</language>
    </title_localized>
    <title_localized>
      <text>Procédé de fabrication d&#39;un milieu poreux en polysulfone approprié à la filtration</text>
      <language>fr</language>
    </title_localized>
    <title_localized>
      <text>Process for the preparation of porous polysulfone media suitable for filtration</text>
      <language>en</language>
    </title_localized>
    <inventor>BEDWELL, WILLIAM B.</inventor>
    <inventor>YATES, STEPHEN F.</inventor>
    <inventor_harmonized>
      <name>BEDWELL WILLIAM B</name>
      <country_code>US</country_code>
    </inventor_harmonized>
    <inventor_harmonized>
      <name>YATES STEPHEN F</name>
      <country_code>US</country_code>
    </inventor_harmonized>
    <assignee>Cpc Engineering Corporation</assignee>
    <assignee_harmonized>
      <name>CPC ENG CORP</name>
      <country_code>US</country_code>
    </assignee_harmonized>
    <entity_status></entity_status>
    <art_unit></art_unit>
  </row>
  <row id="2">
    <publication_number>EP-2309181-B1</publication_number>
    <application_number>EP-10012345-A</application_number>
    <country_code>EP</country_code>
    <kind_code>B1</kind_code>
    <application_kind>A</application_kind>
    <application_number_formatted>EP20100012345</application_number_formatted>
    <pct_number></pct_number>
    <family_id>43332270</family_id>
    <title_localized>
      <text>Installation de chaudière à combustion à oxy-fuel et son procédé de fonctionnement</text>
      <language>fr</language>
    </title_localized>
    <title_localized>
      <text>Oxyfuel combustion boiler plant and operation method of oxyfuel combustion boiler plant</text>
      <language>en</language>
    </title_localized>
    <title_localized>
      <text>Oxyfuel-Brennkessel und Betriebsverfahren dafür</text>
      <language>de</language>
    </title_localized>
    <inventor>TANIGUCHI, MASAYUKI</inventor>
    <inventor>SHIBATA, TSUYOSHI</inventor>
    <inventor>HAYASHI, YOSHIHARU</inventor>
    <inventor_harmonized>
      <name>TANIGUCHI MASAYUKI</name>
      <country_code>JP</country_code>
    </inventor_harmonized>
    <inventor_harmonized>
      <name>SHIBATA TSUYOSHI</name>
      <country_code>JP</country_code>
    </inventor_harmonized>
    <inventor_harmonized>
      <name>HAYASHI YOSHIHARU</name>
      <country_code>JP</country_code>
    </inventor_harmonized>
    <assignee>Mitsubishi Hitachi Power Systems, Ltd.</assignee>
    <assignee_harmonized>
      <name>MITSUBISHI HITACHI POWER SYS</name>
      <country_code>JP</country_code>
    </assignee_harmonized>
    <entity_status></entity_status>
    <art_unit></art_unit>
  </row>
</root>

Here, it automatically added row id=1 row id=2 for the 2 elements which was present in the JSON array.
Can we have a similar feature to add a auto-incrementing xml node for every element present in the JSON?

Output "<class 'dict'>" after every readfromjson()

Hi!

I don't know if this is a real issue, but from version 2.2.1 to 3.0.0, after every readfromjson() call, the console prints "<class 'dict'>" (assuming type(returnVar));

The line below represents my code:
jData = readfromjson("\\localhost\POS_JOGO\AutoUpdaterBRAsB.json")

json from string

Would you be able to add a method to get the json from a string rather than a file path or URL please?

Boolean types are not converted to their XML equivalents.

Describe the bug
When converting a JSON object with boolean type values, Json2xml is not converting the values to their XML equivalents. Json2xml should be exporting the values in the XML as the lowercase words true and false respectively. Instead, Json2xml is exporting them as Python boolean types using the capitalized words True and False.

To Reproduce
Steps to reproduce the behavior:

  1. Given the following JSON object:
{
      "boolean": true,
      "boolean_dict_list": [
        {"boolean_dict": {"boolean": true}},
        {"boolean_dict": {"boolean": false}}
      ],
      "boolean_list": [true, false]
}
  1. Calling the Json2xml conversion like so:
xml = json2xml.Json2xml(sample_json, pretty=True).to_xml()
  1. Produces the following XML:
<all>
        <boolean type="bool">True</boolean>
        <boolean_dict_list type="list">
                <item type="dict">
                        <boolean_dict type="dict">
                                <boolean type="bool">True</boolean>
                        </boolean_dict>
                </item>
                <item type="dict">
                        <boolean_dict type="dict">
                                <boolean type="bool">False</boolean>
                        </boolean_dict>
                </item>
        </boolean_dict_list>
        <item type="bool">True</item>
        <item type="bool">False</item>
</all>

Notice all the boolean values are capitalized instead of being lowercase like they should be in XML and JSON. There also seems to be a problem with the boolean_list array, it is missing its parent tag.

Expected behavior

Json2xml should produce an XML string that looks like this:

<all>
        <boolean type="bool">true</boolean>
        <boolean_dict_list type="list">
                <item type="dict">
                        <boolean_dict type="dict">
                                <boolean type="bool">true</boolean>
                        </boolean_dict>
                </item>
                <item type="dict">
                        <boolean_dict type="dict">
                                <boolean type="bool">false</boolean>
                        </boolean_dict>
                </item>
        </boolean_dict_list>
        <boolean_list type="list">
            <item type="bool">true</item>
            <item type="bool">false</item>
        </boolean_list>
</all>

Additional context

The problem with the capitalized boolean values is because of the following statements in the json2xml.dicttoxml module:

def convert(obj, ids, attr_type, item_func, cdata, item_wrap, parent="root"):
    """Routes the elements of an object to the right function to convert them
    based on their data type"""

    LOG.info(f'Inside convert(). obj type is: "{type(obj).__name__}", obj="{str(obj)}"')

    item_name = item_func(parent)

    # Booleans are converted using this function because a Python boolean is a subclass of Number
    if isinstance(obj, (numbers.Number, str)):
        return convert_kv(
            key=item_name, val=obj, attr_type=attr_type, attr={}, cdata=cdata
        )

    if hasattr(obj, "isoformat"):
        return convert_kv(
            key=item_name,
            val=obj.isoformat(),
            attr_type=attr_type,
            attr={},
            cdata=cdata,
        )

    # This is never evaluated because Python booleans are subclasses of Python integers
    if isinstance(obj, bool):
        return convert_bool(item_name, obj, attr_type, cdata)

Python booleans are subclasses of integers, so the boolean values are passed to convert_kv instead of convert_bool because an integer is also a numbers.Number. The following statements evaluate to True in Python:

# Booleans are integers
isinstance(True, int)

# Booleans are numbers
isinstance(True, numbers.Number)

# Booleans are booleans
isinstance(True, bool)

Adjust six requirement

Is there any possibility to loosen six requirement (or even remove it)?
It doesn't look like it is even used anymore, and it greatly conflicts with other packages that require different versions.

TypeError: 'bool' object does not support item assignment

I see someone had reported this problem in
https://gitmemory.com/issue/vinitkumar/json2xml/59/657379816

I am using json2xml 3.5.0
C:\Programming\PycharmProjects\Monaco_Contours>pip freeze | grep json2xml
json2xml==3.5.0
(json2xml needs xmltodict-0.11.0, though I have tried both xmltodict-0.11.0 and xmltodict-0.12.0).

Still see the same issue:
File "C:\Users\usjimat\AppData\Local\Programs\Python\Python38\lib\site-packages\dicttoxml.py", line 333, in convert_kv
attr['type'] = get_xml_type(val)
image

SyntaxError: invalid syntax

After running the code like

python -m src.cli --url="https://coderwall.com/vinitcool76.json"

I'm getting the next error, but it exports the file. I think that the file is complete. I'm posting this just to be sure.

Traceback (most recent call last): File "/usr/lib/python2.7/runpy.py", line 162, in _run_module_as_main "__main__", fname, loader, pkg_name) File "/usr/lib/python2.7/runpy.py", line 72, in _run_code exec code in run_globals File "/usr/local/lib/python2.7/dist-packages/src/cli.py", line 4, in <module> from src.json2xml import Json2xml File "/usr/local/lib/python2.7/dist-packages/src/json2xml.py", line 23 def __init__(self, data: str) -> None: ^ SyntaxError: invalid syntax

Usage example syntax issue

Describe the bug
On https://pypi.org/project/json2xml/ The usage example has an error in it. Second from should be import.

... from json2xml.utils from readfromurl, readfromstring, readfromjson ...
should be
... from json2xml.utils import readfromurl, readfromstring, readfromjson ...

Custom wrapper not working on 2.2.1

I can't seem to make the custom Json2xml(data, WRAPPER, INDENT) to work. Keeps returning "unexpected keyword argument 'wrapper'".
Also did not found any implementation of it on the json2xml.py src code.

  • OS: Windows 7 x64

wrapper=None?

When I use the 'wrapper' argument with a 'None' value, it still prints a root element:

JSON_DATA = readfromjson('data.json')
XML_DATA = json2xml.Json2xml(JSON_DATA, wrapper=None, pretty=True).to_xml()
print(XML_DATA)


<?xml version="1.0" ?>
<None>
  <field1 type="str">123</field1>
  <field2 type="str">abc</field2>
</None>

It's treating 'None' and even 'False' and 'True' as strings. Not sure if this is intentional.
Looks like a bug to me, but in any case a way to prevent creating a root element would be appreciated.
I normally use this to test for XML parsers (XML injection) on APIs by changing the json request to xml format, and many times it is not necessary to submit a root element; the backend server takes care of appending it to your request to make it a valid XML document.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.