How to convert xml string in given format to json? - javascript

When i try to read xml data from Ajax response
xmlDoc = data[0].body;
alert(xmlDoc);
i got below string of xml string
"<VNET><ID>0</ID><UID>0</UID><GID>0</GID><UNAME>oneadmin</UNAME><GNAME>oneadmin</GNAME><NAME>vnet</NAME><PERMISSIONS><OWNER_U>1</OWNER_U><OWNER_M>1</OWNER_M><OWNER_A>0</OWNER_A><GROUP_U>0</GROUP_U><GROUP_M>0</GROUP_M><GROUP_A>0</GROUP_A><OTHER_U>0</OTHER_U><OTHER_M>0</OTHER_M><OTHER_A>0</OTHER_A></PERMISSIONS><CLUSTER_ID>-1</CLUSTER_ID><CLUSTER></CLUSTER><TYPE>0</TYPE><BRIDGE>bro</BRIDGE><VLAN>0</VLAN><PHYDEV/><VLAN_ID/><GLOBAL_PREFIX/><SITE_PREFIX/><RANGE><IP_START>192.168.5.2</IP_START><IP_END>192.168.5.254</IP_END></RANGE><TOTAL_LEASES>0</TOTAL_LEASES><TEMPLATE><DNS><![CDATA[192.168.5.1]]></DNS><GATEWAY><![CDATA[192.168.5.1]]></GATEWAY><NETWORK_ADDRESS><![CDATA[192.168.5.0]]></NETWORK_ADDRESS><NETWORK_MASK><![CDATA[255.255.255.0]]></NETWORK_MASK></TEMPLATE></VNET>"
so to avoid Html parsing in javascript. I want actual xml formate string.
ex:
"<VNET><ID>0</ID><UID>0</UID></VNET>"
want like
"<VNET><ID>0</ID><UID>0</UID></VNET>"
Any One please help me

The following answer would do what you're looking for, but it would be better to ensure the XML is not encoded in the original data response.
https://stackoverflow.com/a/14227660/463205

Related

Decode a JSON String in Javascript

I have a encoded JSON string returning the following sting which I am displaying on my webpage from a database call.
{"Value 1":"1234","Value 2":"123456"}
How do I decode this string and also format the data to be displayed in a table?
I am at a lost as how to do this. Thanks
Here is how to turn a string containing a JSON into an object:
JSON.parse('{"Value 1":"1234","Value 2":"123456"}');

JavaScript Encoding & Decoding Error

I am getting an issue with Javascript Encoding and Decoding. I have a json object which contains a string encoded in UTF-8 like 'R\xc3\xa9union'. To ensure that the Javascript file correctly displays the string, I'm adding an attribute charset to the script tag. The json object is in countries.js. I'm including countries.js as <script src="js/countries.js" charset="UTF-8"></script> and yet it is still being displayed as Réunion instead of Réunion. Any suggestion?
Use escape() combined with decodeURIComponent():
decodeURIComponent(escape('R\xc3\xa9union'));
That should do the trick:
escape('R\xc3\xa9union'); // "R%C3%A9union"
decodeURIComponent("R%C3%A9union"); // "Réunion"
Now, you said you couldn't do this manually for all the places you need strings from the JSON. I really don't know a way to automate this without re-building the JSON with JS, so I'd suggest writing a little "wrapper" function to decode on the fly:
function dc(str){
return decodeURIComponent(escape(str));
}
You can then decode the required strings with minimal effort:
var myString = dc(myJson["some"]["value"]);
Now, what else could work, but is a little more risky: JSON.stringify() the entire object, decode that using the 2 functions, then JSON.parse() it again.

How to convert formatted string to regularly javascript dictionary?

I get formatted json string with all \ before " and \n for newlines.How to convert this string to regularly javascript dictionary ?
I thought to replace all \n with '' and \" with " but it is kinda bruteforce solution. Is there moreelegant way ?
It sounds like you're receiving JSON encoded data. To convert the raw data into an object, use the JSON.parse function:
var test = "{\"foo\":\"bar\"}";
var data = JSON.parse(test);
console.log(data);
I am not sure I understand what you mean by 'JavaScript dictionary' exactly but in my experience the easiest way to convert a JSON string to any kind of usable JavaScript object is to use JSON.parse, see Parse JSON in JavaScript? for some good information on this.
Also in future a small sample of what you are trying to do, your source data etc. would be helpful!
It's a escaped string, you should unescape it and using eval will return the object represented by the json string. A JSON string is simply a javascript serialized object, so you may eval'd with javascript and will return the "map" or object that represents.
Newlines are valid in json so you don't require to remove them.
var o = eval("o = {name:\"test\"}");
alert(o.name);
You're probably thinking of a dictionary implementation as you'd find in other languages such as Objective C or C# - JavaScript does not have a dictionary implementation. So is your question how to parse JSON so you can get some values into key value pairs? If so then it sounds like JSON.parse is going to work for you.
If your question is about how to implement something like a dictionary in JavaScript, with data populated from JSON - then you'll want to parse the JSON and set up some simple JavaScript objects to act like a dictionary:
var dictionary = {"key1":"hello", "key2":"hello2", "key3":"hello3"};
console.log(dictionary["key3"]); // gives the value "hello3"

Trying to parse JSON string, unexpected number

I am trying to parse this JSON:
var json = '{"material":"Gummislang 3\/4\" 30 m (utanp\u00e5liggande sk\u00e5p)"}'
I run JSON.parse(json) but i get the error SyntaxError: Unexpected number when doing so. I have tried this in Google Chrome. I don't know what the problem is since I can take the JSON string and put it in any JSON validator and it claims that the JSON is valid. Shouldn't the browser be able to parse it?
You are inserting a JSON object representation into a JavaScript string without properly escaping the representation.
To avoid having to do this, remove the quotes you are adding around the representation, and skip the JSON.parse(json) – the default output from PHP's json_encode() is valid JavaScript when used in this context.
For security, you should specify the JSON_HEX_TAG option if possible. This will prevent cross-site scripting in cases where the JSON might end up inside a document parsed as XML. (And for XML documents, the JSON should be inside a CDATA section as well.)
You're validating the string literal, which is a valid JSON string containing invalid JSON. You need to validate the value of the string, which is not valid JSON.
If you paste the string value into a JSON validator, you'll see that the error comes from this part:
"material": "Gummislang 3/4"30m
The " needs to be escaped.

Parsing JSON response

I am new to using JSON. On subscribing to a webservice I receive a json response as given below.
1024760833990-36891Customercustomer realtime20110914 10:48:10NNNYYYYN{"hostName":"uat91w82m7","data":{"view":{"columnValues":[{"DisplaySymbol":"MSFT Jan 19 '13 $35 Call","Symbol":"MSFT--130119C00035000","Quantity":1.0,"Price":0.71,"ChangeValue":0.01,"ChangePercentage":1.41,"DaysGainValue":1.0,"PriceAdjusted":false}],"columnHeaderCodes":[1,2,3,4,11,5],"viewName":null,"quoteType":0,"accountNumber":"39903689","asOfDate":1316022555984,"totalMarketValue":"71.0","todaysGainValue":"1.0","annualGainValue":"0.0","pagination":{"nextPositionMarker":"","pageNumber":1,"posPerPage":500,"posDetailPerPage":50,"totalNumberofPositions":1,"markerLength":0},"viewType":3,"portfolioId":null,"customView":false,"displayNetWorth":1,"groupOptions":"G0","viewID":null,"widgetType":null,"columnHeaders":null,"totalPositionCount":0,"easternDaylight":true,"widget":false}},"smUser":"102476083","success":true,"sysdate":1316022555992,"message_info":null,"message_type":null}
I am trying to display certain parameters on my page. So how to I parse it.
ANSWER : just remove 1024760833990-36891Customercustomer realtime20110914 10:48:10NNNYYYYN through PHP or any other server side script and them parse it to jQuery, i'm damn sure it will do the job.
First paste your JSON into JSONLint.com to make sure it's valid JSON. What you provided in your question is not valid.
Secondly you can parse it with JQuery using parseJSON or with old skool JS using JSON.parse.
As long as you have a correctly formatted JSON string, all you have to do is use JSON.parse(string).
var JSON_string='{"name":"Jason","age":22}';
var JSON_object=JSON.parse(JSON_string);
console.log(JSON_object.name+' is '+JSON_object.age);

Categories

Resources