Decode a JSON String in Javascript - 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"}');

Related

UINT8 Array to String without escape characters

I'm parsing a Uint8 array that is an HTML document. It contains a script tag which in turn contains JSON data that I would like to parse.
I first converted the array to text:
data = Buffer.from(str).toString('utf8')
I then searched for the script tag, and extracted the string containing the JSON:
... {\"phrase\":\"Go to \"California\"\",\"color\":\"red\",\"html\":\"<div class=\"myclass\">Ok</div>\"} ...
I then did a replace to clean it up.
data = data.replace(/\\"/g, "\"").replace(/\\/g, "").
{"phrase":"Go to "California"","color":"red","html":"<div class="myclass">Ok</div>"}
I tried to parse using JSON.parse() and got an error because the attributes contain quotes. Is there a way to process this further using a regex ? Or perhaps a library? I am working with Cheerio, so can use that if helpful.
The escape characters are necessary if you want to parse the JSON. The embedded quotes would need to be double escaped, so the extracted text isn't even valid JSON.
"{\"phrase\":\"Go to \\\"California\\\"\",\"color\":\"red\",\"html\":\"<div class=\\\"myclass\\\">Ok</div>\"}"
or, using single quotes:
'{"phrase":"Go to \\"California\\"","color":"red","html":"<div class=\\"myclass\\">Ok</div>"}'
Thanks.
After some more tinkering around, I realized that I should have encoded the data to Uint8 at the source (a Lambda function) before transmitting it for further processing. So now, I have:
Text
Encoded text to Uint8
Return from Lambda function.
Decode from Uint8 to text
Process readily as no escape characters.
Before, I was skipping step 2. And so Lambda was encoded the text however it does by default.

How to convert JSON Parse object property into array?

In mysql database, "diagID" is saved as json_encoded(array). Now i need it to retrieve in ajax success.
How to convert JSON parse data into array, as it's showing string?
var ajaxResponse= {
"id": "123",
"diagID" : "['101','125','150','230']"
}
typeof(ajaxResponse.diagID)
= string
In javascript typeof(ajaxResponse.diagID) shows string. How to convert it into array?
Decoding it in php would make most sense
$diagID = json_decode($diagID, true);
Then when you json_encode() the whole response it won't have the extra wrapping quotes.
Note however that the strings in array have single quotes which are not valid json and need to be replaced with double quotes before they can be parsed in either language

How to encode and decode query string from javascript to servletpage using java?

How to encode and decode query string from javascript to servletpage
Javascript
var page=http://localhost/jsp/index.jsp?pname=jack & sparrow&price=$20&rate=10 - 20%
$('#listContent').load(page);
I got 404 error
var page=http://localhost/jsp/index.jsp?pname=titanic&price=10&rate=12
$('#listContent').load(page);
this one working fine
how to pass if query string contain space and special symbols
how to encode it and how to pass this query string
if it is encoded how to decode in servlet page
My expected output as
String pname=request.getParameter("pname")
String price=request.getParameter("price")
String rate=request.getParameter("rate")
pname=jack & sparrow
price=$20
rate=10 - 20%
On the Javascript side you have to encode it using function encodeURIComponent(yourString)
If you want to decode such string on Java side, you can do it using (for example) new java.net.URI(receivedString).getPath()

How to convert xml string in given format to json?

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

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"

Categories

Resources