abdolence / x2js Goto Github PK
View Code? Open in Web Editor NEWx2js - XML to JSON and back for JavaScript
x2js - XML to JSON and back for JavaScript
I tried to find there, an aparently there are some forks with the same name published.
Hello, we have develope an app that included a link to the js file at https://x2js.googlecode.com/hg/xml2json.js
But this morning we saw that this link is not working...we has include the js inside the app to solve the problem and it runs.
The problem is that until iTunes validates the app update, our clients cannot use it.
Does anyone know where must I notify this issue to Googlecode to solve it?
Thanks!!
Hi,
I have this weird issue on parsing xml to json with our application integrated inside our clients app. Our client launched our app inside an iframe and they are getting an issue with date showing as NaN. X2JS parses 1979-09-25T00:00:00-05:00 as object with __text property and the value is 1979\n-\n09\n-\n25T00:00:00\n-\n05:00. And this is only happens in IE11 when our application is inside our clients app. But when we launched our application outside clients app (by putting the url directly to the browser) it is parsing as string dateOfBirth: "1979-09-25T00:00:00-05:00". Would somebody help us with this or any thought on why is this happening? Thank you.
Many thanks for sharing this greate library, but I have two problems:
Problem
If there's a : in the xml tag, I get the followin error:
Uncaught TypeError: Cannot read property 'Subscription' of null
at xmltojson (Own.html:22)
at onload (Own.html:42)
XML content is the following:
"ns:2flagsnu</ns:2flags>"
Problem
If there's a " instead of a ' I get the following error:
Uncaught SyntaxError: Unexpected number
XML content is the following:
""
Is there a way to fix this?
Please update fixed code.
xml2json.zip
We at VersionEye are working hard to keep up the quality of the bower's registry.
We just finished our initial analysis of the quality of the Bower.io registry:
7530 - registered packages, 224 of them doesnt exists anymore;
We analysed 7306 existing packages and 1070 of them don't have bower.json on the master branch ( that's where a Bower client pulls a data ).
Sadly, your library abdmob/x2js
is one of them.
Can you spare 15 minutes to help us to make Bower better?
Just add a new file bower.json
and change attributes.
{
"name": "abdmob/x2js",
"version": "1.0.0",
"main": "path/to/main.css",
"description": "please add it",
"license": "Eclipse",
"ignore": [
".jshintrc",
"**/*.txt"
],
"dependencies": {
"<dependency_name>": "<semantic_version>",
"<dependency_name>": "<Local_folder>",
"<dependency_name>": "<package>"
},
"devDependencies": {
"<test-framework-name>": "<version>"
}
}
Read more about bower.json on the official spefication and nodejs semver library has great examples of proper versioning.
NB! Please validate your bower.json with jsonlint before commiting your updates.
Thank you!
Timo,
twitter: @versioneye
email: [email protected]
VersionEye - no more legacy software!
Hi guys.
I've tried to install your library using npm but get the following issue:
$ npm install git+https://github.com/abdmob/x2js.git --save
npm ERR! addLocal Could not install /tmp/npm-6604-622e8ec5/git-cache-30c70c4a6eeb/41782e9b53e2c4093873ea8d761805ae1935d753
npm ERR! Linux 3.19.0-39-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" "git+https://github.com/abdmob/x2js.git" "--save"
npm ERR! node v4.2.4
npm ERR! npm v2.14.12
npm ERR! Invalid name: "abdmob/x2js"
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR! <https://github.com/npm/npm/issues>
I think you need to remove the forwardslash from the package name in package.json
x2js is great! But, facing the below issues... can you provide solution for it?
<tree>
<node1>
textTextText
<subnode1> text1 </subnode1>
<subnode2> text2 </subnode2>
</node1>
</tree>
when doing xml to json
{
"tree": {
"node1": {
"subnode1": "text1",
"subnode2": "text2",
"__text": "textTextText"
}
}
}
<tree>
<node1>
<subnode1>text1</subnode1>
<subnode2>text2</subnode2>
textTextText
</node1>
</tree>
As you can see, the text nodes are pushed to last when reconverting.
Is it possible to avoid getting "" in numeric values when converting XML to JSON
<xml><a>String</a><b>3</b></xml>
yeilds {"xml":{"a":"String","b":"3"}}
instead of
{"xml":{"a":"String","b":3}}
When trying to convert from a Json Object having single quotes, slashes, colons etc to xml, the output prints the ascii values instead of the symbols.
For Example:
Lets say a part of my Json Object looks some thing like this
"Object { value : " id='480' name='USEclipse' status='1'}"
Then the XML generated would have the values as
id='480' name='USEclipse'
On firefox 51.0.1 (32-bit) the error below is thrown whenever this library is used. Still works just a syntax error is reported
XML Parsing Error: syntax error Location: file:///C:/Downloads/x2js-1.2.0/demo.html Line Number 1, Column 1:
OR
When converting from JSON to XML I get invalid XML element names such as <0> and that is not allowed. Perhaps they should be escaped in some way.
Example, this JSON:
"deMag": [
{
"settings": {
"generator": 1,
"startCurrent": 5
},
"data": [ { } ]
}
],
produce this XML:
<deMag>
<settings>
<generator>1</generator>
<startCurrent>5</startCurrent>
</settings>
<data>
<$H>7535</$H>
</data>
</deMag>
Facing this issue even I'm using your code.
var xmlText = "<testns:MyOperation xmlns:testns='http://www.example.org'>"+
"Success"+
"ddsfgdsdgfdgfdtestArrSize</testns:MyOperation>";
var jsonObj = x2js.xml_str2json( xmlText );
When trying to figure out the parsererrorNS by parsing the 'INVALID' string IE11 and Edge actually log an error within the parseXMLString function.
Is there any reason to use the parsererrorNS to see whether a parsed xmlDoc contains an error as opposed to just looking for the parsererror tag directly?
I would think doing xmlDoc.getElementsByTagName("parsererror").length > 0 should work to figure out whether there was an error with no need for the namespace
To prevent this,
I added the below code to parseXmlString func
// IE9+ now is here
if(!isIEParser) {
try {
parsererrorNS = parser.parseFromString("INVALID", "text/xml").getElementsByTagName("parsererror")[0].namespaceURI;
}
catch(err) {
parsererrorNS = null;
}
}
else {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlDocStr);
return xmlDoc;
}
For some reason var x2js = new X2JS()
is failing on IE, it keeps giving X2JS is undefined
I tried doing an ajax call to my API which returns a JSON and trying to convert it to XML, this is working okay on other browsers except IE 11.
This is what I'm trying to do.
$.get(apiUrlPath) .then(function (data) { var x2js = new X2JS(); var json2XMLResult = x2js.json2xml_str(data); console.log(data, json2XMLResult) })
Any ideas why its failing on IE11, although the jsfiddle example seems to be okay on IE.
I've put this in my index.html
<script src="https://cdn.rawgit.com/abdmob/x2js/master/xml2json.js"></script>
json2xml_str is not working, i tried also the exmaple from readme, the result is always empty (empty string?)
xml_str2json is working perfectly
jsfiddle demo do not work anymore
UPDATE!
Now by magic it still work ??????
http://jsfiddle.net/abdmob/gkxucxrj/1/
The code uses a lot of instanceof and instanceof lies when a value comes from another frame or iframe.
This means that jsonObj instanceof Object
needs to be replaced with typeof(jsonObj) === 'object'
or some other workaround. See http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/ for some ideas.
Hi,
When I used this library on my product with another libraries, occurs this javascript error: "Uncaught TypeError: (intermediate value)(…) is not a function".
I think that cause of the problem is a missing semicolon end of the wrapper function. Detail is here: https://stackoverflow.com/a/42036382
Thanks.
Hi,
Is it possible to provide a few Git tags that correspond to various versions of the library? It will enable us to use a specific version in bower as opposed to an empty one - ""
.
I'd like to have a possibility to specify an options which would force the lib create keys in camel keys for JSON object. And back.
A standard way of handling null in an XML is to do this:
<thing i:nil="true"></thing>
which translates to:
{ "thing": null }
This is different than just having an empty clause:
<thing></thing>
which translates to:
{ "thing":"" }
Actually the version on tag of xml2json is 1.1.5 or Master contains 1.1.7. Is it possible to create a new tag or delete and recreate the tag ?
for the xml in file sample.txt :
sample.txt
:
its giving output( stringified ) as:
The unexpected part here is "RejectReason":["",""]
, need to figure out how "shishir reason" converted as ":["",""]" actually it is array of 2 blank strings
Hi,
Thanks for x2js,
I am trying to convert the below XML content to JSON using "xml_str2json" but returning null.
<item> <category>Scarlett Johansson</category> <category>Movies</category> <category>Entertainment</category> <merlin:image orientation="landscape">omNMmo6Ony6</merlin:image> </item>
when I am removing <merlin:image... line it is working fine. So, tell what should I do to convert the above structure into JSON.
Hi
I can't find the way/format of the JSON object for generating the following XML (with the same order)
<parent>
<id>a</id>
<value>aa</value>
<id>b</id>
<value>bb</value>
</parent>
The order of the tags is crucial for me.
If you will try the above xml in the jsfiddle test page you will notice that after pressing the XML -> JSON and JSON -> XML the original XML will be replaced by a new with different order of the nodes (which is bad for me).
Any ideas?
Sorry to ask, but no license is defined for your work. Any move to choose a license that would enable us to use and share your code ? See https://choosealicense.com/no-license/ when you don't select any.
Regards.
Let's try the following XML:
<data>
<totalrows>2</totalrows>
<rows>
<row>
<prop1>A</prop1>
<prop2>B</prop2>
<prop3>C</prop3>
</row>
<row>
<prop1>D</prop1>
<prop2>E</prop2>
<prop3>F</prop3>
</row>
</rows>
</data>
x2js converts it to this JSON:
{
"data": {
"totalrows": "2",
"rows": {
"row": [
{
"prop1": "A",
"prop2": "B",
"prop3": "C"
},
{
"prop1": "D",
"prop2": "E",
"prop3": "F"
}
]
}
}
}
Look at <rows>
element. Basically it's a container for collection of <row>
elements. In other words, <rows>
should naturally be translated to "rows":[...]
, where each <row>
should be an object (anonymous, because of javascript nature):
{
"data": {
"totalrows": "2",
"rows": [
{
"prop1": "A",
"prop2": "B",
"prop3": "C"
},
{
"prop1": "D",
"prop2": "E",
"prop3": "F"
}
]
}
}
But instead, x2js translates <rows>
to an object with the only one property <row>
which is array.
When I'm trying to use this config to translate <rows>
to array:
{ arrayAccessFormPaths : ["data.rows"] }
then I'm getting this result:
{
"data": {
"totalrows": "2",
"rows": [
{
"row": [
{
"prop1": "A",
"prop2": "B",
"prop3": "C"
},
{
"prop1": "D",
"prop2": "E",
"prop3": "F"
}
]
}
]
}
}
which makes "rows"
an array containing one object with (again) the only one "row"
element which in turn is array of actual objects. And this doesn't make much sense.
Is there a way to get a natural array translation in x2js? If we care about array's elements names, it's possible to add an accessor to the array'ed object, like this:
{
__object_name: "row",
"prop1": "A",
"prop2": "B",
"prop3": "C"
}
XML to JSON conversion is not working in IE
Just update the docs :)
Great lib!
Hi, thanks for the great tool !
i have a question though..
having:
xml1 = '<root><tag>word</tag></root>'
and
xml2 = '<root><tag attr="1">word</tag></root>'
they transform to
{"root":{"tag":"word"}}
and
{"root":{"tag":{"_attr":"1","__text":"word"},}}
is there a way to tranform all tags to objects with __text
property indipendently of presence of attributes?
So to keep consistency on json structure ..
Tested with config options, without success:
emptyNodeForm :"object"
skipEmptyTextNodesForObj : false
keepCData : true
enableToStringFunc : false
When an xml file contains an empty node, the parser returns an exception. The empty node that it can't handle is
<p />
I configured to X2JS to use emptyNodeForm : "text" but the parser is still returning an exception.
I'm trying to use this library in Zotero standalone (4.0.29), which is based on Firefox 48 which I think should support most of ECMAScript 6... however I get an error "module is not defined". Seems like there's something up with the environment, but the library description says there are no dependencies.
Is this designed to be working standalone? Or can I install via npm install?
Hi, not sure if I'm doing something wrong here but I'm getting the following issue "ReferenceError: X2JS is not defined". Any help would be greatly appreciated.
Thanks
server:test chris$ cat package.json
{
"name" : "myapp",
"version" : "0.0.1",
"main" : "main.js",
"dependencies": {
"x2js": "^3.1.0"
}
}
server:test chris$ npm install x2js
[email protected] /Users/chris/scripts/tapps_proj/test
└── [email protected]
npm WARN [email protected] No description
npm WARN [email protected] No repository field.
npm WARN [email protected] No license field.
server:test chris$ node main.js
/Users/chris/scripts/tapps_proj/test/main.js:4
var x2js = new X2JS();
^
ReferenceError: X2JS is not defined
at Object. (/Users/chris/scripts/tapps_proj/test/main.js:4:16)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:420:7)
at startup (bootstrap_node.js:139:9)
at bootstrap_node.js:535:3
server:test chris$ cat main.js
require('x2js');
// Create x2js instance with default config
var x2js = new X2JS();
var xmlText = "Successval1val2";
var jsonObj = x2js.xml_str2json( xmlText );
That bower name is causing bower to save the entry like this
Which causes this error on bower install
ECMDERR Failed to execute "git ls-remote --tags --heads abdmob/x2js=https://github.com/abdmob/x2js.git", exit code of #128 fatal: I don't handle protocol 'abdmob/x2js=https'
All because of the foward-slash... a rename could save other people some surprises.
like the one i got when my build failed on bower install
Is it possible to convert boolean value in their string formats into actual true or false values, when converting from XML to JSON? We have a usecase where the string version of "true" does not fill in for actual true value.
Currently our project uses version 1.0.11, and we set attributePrefix to ''
.
We are looking at upgrading to the latest version, but this will not allow attributePrefix to be an empty string since empty strings are falsy and therefore config.attributePrefix || "_"
returns "_"
.
It would be great if x2js explicitly checked for undefined for this option rather than falsy-ness.
Hi,
I used the function json2xml_str which get a json object and returned xml string
This function return the xml not with full closing tag :
''
instead of:
''
It is make me problems,
how can I get the xml string with full closing tags?
Thanks,
Reizy
Now when I try to convert
{ul: [{li: 1}, {li: 2}]}
it becomes
<ul><li>1</li></ul><ul><li>2</li></ul>
How can I remove duplicated <ul>
tag? Thanks
You might want to add escaping/unescaping for invisible control character, which I ran into:
...
function escapeXmlChars(str) {
if (typeof str === "string") {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/\//g, '/')
.replace(/\r/g, '
')
.replace(/\n/g, '
')
.replace(/\t/, '	')
.replace(/ /, ' ');
}
return str;
}
function unescapeXmlChars(str) {
return str.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'")
.replace(///g, '\/')
.replace(/
/, '\r')
.replace(/
/, '\n')
.replace(/	/, '\t')
.replace(/ /, ' ');
}
...
I was trying to remove a property from the output XML using jsonPropertiesFilter, but no matter what I put in the array, it removes all properties.
var converter = new x2js({
// Escaping XML characters. Default is true from v1.1.0+
escapeMode: true,
// XML attributes prefix. Default is "_"
attributePrefix: "_",
// Array access form (none|property).
// Use this property if you want X2JS generate additional property <element>_asArray
// to access in array form any element
// Default is 'none' from v1.1.0+
arrayAccessForm: "none",
// Handling empty nodes (text|object).
// When X2JS found empty node like <test></test> it will be transformed to test : '' for 'text' mode,
// or to Object for 'object' mode
// Default is 'text'
emptyNodeForm: "text",
// Enable/Disable auxiliary function in generated JSON object to print text nodes with __text/__cdata
// Default is true
enableToStringFunc: true,
// Array access paths (array).
// Use this option to configure paths to XML elements always in "array form".
// You can configure beforehand paths to all your array elements based on XSD or your knowledge
// about XML structure
// Every path could be a simple string (like 'parent.child1.child2'), a regex (like /.*\.child2/), or a custom function
// Default is empty array
arrayAccessFormPaths: [],
// Strip whitespaces (trimming text nodes)
stripWhitespaces: true,
// Skip empty text tags for nodes with children
skipEmptyTextNodesForObj: true,
// DateTime access paths (array).
// Use this option to configure paths to XML elements for "datetimes form".
// You can configure beforehand paths to all your array elements based on XSD or your knowledge
// about XML structure
// Every path could be a simple string (like 'parent.child1.child2'), a regex (like /.*\.child2/), or a custom function
// Default is empty array
datetimeAccessFormPaths: [],
jsonPropertiesFilter: ['TYPE_NAME']
});
var XMLstring = converter.json2xml_str(jObj);
I'm using x2js.json2xml_str() to generate XML files from JSON. This call outputs an unindented string that is unreadably by humans. It would be great to be able to pretty print resulted XMLs. I've briefly looked into the code of x2js but couldn't find anything helpful.
Is pretty printing currently supported?
Hi,
It's a very great tool,
I'm looking to use in node server, is it possible? for now I'm facing problem with window object error.
Could you help me with that ?
thanks a lot
I am trying to parse an XML where some elements have a single attribute xsi:nil="true"
and no contents.
But it parses it to:
{ _xsi:nil: "true" }
Would it be possible to delete those elements?
Is it possible to make lib supports plugins ?
For example, to register functions-transformers which would be called during parsing to transform values/keys/attributes ?
I am using Firefox 43.0 and X2JS 1.2.0 on a current 64 bit Linux box. Everything works fine on Chrome. When I run the following code on Firefox it gives me a syntax error in the console of their debugger (F12):
var x2js = new X2JS();
var xmlText = "<MyRoot><test>Success</test><test2><item>val1</item><item>val2</item></test2></MyRoot>";
var jsonObj = x2js.xml_str2json( xmlText );
I also get a syntax error when I run your similar fiddle. The line referenced is the first line of the html file. (which contains ). Not sure what to do.
Thanks!
I added x2js on my bower.json file
"x2js": "~1.2.0"
Then add in my main.js requirejs config file
paths: {
'x2js': '../vendor/x2js/xml2json.min'
....
}
shim: {
'x2js' : {
exports : 'X2JS'
},
....
'admin-lte' : {
deps: [
'jquery',
'jquery.bootstrap',
'toastr',
'bootstrap-datepicker',
'jquery.transform',
'x2js'
]
}
}
In my script
var x2js = new X2JS();
var json_obj = x2js.xml_str2json(xml_str);
console.log('module [json obj]: ', json_obj);
I've this error:
ReferenceError: X2JS is not defined
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.