Outputting JSON object by key - javascript

I have a JSON string that looks like this:
{"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]}
In Javascript, I'm trying to output the strings by category (cat1-3), this is my code so far.
$.post(loadUrl, function(data){
$("#result").html("<p>Cat1: " + data.cat1 + "</p><p>Cat2: " + data.cat2 + "</p>");
});
I would normally not use JSON (Usually JSTL) but since I want to learn AJAX, I want to try output the cat1-3 values by the key, which I keep getting "undefined".
I was using this as a guide to get the values: http://www.skill-guru.com/blog/2010/01/27/json-javascript-tutorial/

Try below script
va response = {"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]}
var obj = jQuery.parseJSON(response);
alert(obj.cat1);
it will return m1

var a = JSON.parse("{\"cat1\":\"m1\",\"cat2\":[\"d1\",\"d2\",\"d3\"],\"cat3\":[\"m1\",\"m2\",\"m3\",\"m4\"]}");
for(key in a)
{
alert(key);
alert(a[key]);
}

Related

How can I show information from a JSON in HTML in a readable manner without knowing its structure and data?

I have a JSON but I don't know its structure (the key/value pairs that are coming in), and I need to show that info in html. I parse the string that is coming, and loop it to be able to show the info on the page in a nice manner.
<script type="text/javascript" language="JavaScript">
var jsonString = '#{CertificadoBean.certificado.resumen}';
var myObj = JSON.parse(jsonString);
for ( var x in myObj) {
if (myObj[x] instanceof Array) {
document.getElementById("json").innerHTML += "<p>" + "" + "<b>" + x + "</b>" + ": "+JSON.stringify(myObj[x]);
}
else {
document.getElementById("json").innerHTML += "<p>" + "" + "<b>" + x + "</b>" + ": " + myObj[x];
}
}
</script>
However in some cases it'll print out this:
Nivel matriculado: 10
Periodo matriculado: 2019-02
Periodos matriculados: 10
Cursos pendientes:[{"Cod.":"NIP01","Nivel":9},{"Cod.":"NI043","Nivel":10},{"Cod.":"ALE10","Nivel":10}]
I have a problem with displaying the info a nice manner when the loop finds an array in the json, and I'm not sure how to properly loop the array to display in a legible manner like the rest of the object.
How do I make Cursos pendientes show nicely like the others?
To do this, you should use JSON.stringify in javascript.
var str = JSON.stringify(obj, null, 2);
Where obj is your json. null is a replacer function ( dont use ), and 2 is a spacer ( spacing when printing )
Then you can place the stringified json on the page
document.body.innerHTML = str
See more here: Mozilla Developer Json.stringify Reference
You can wrap your JSON in a <code> or <pre> tag for a nice preview
If you really want to output it as plain html you could use some recursion (and maybe for better layout some lists). By the recursion you can ensure that all the properties (in array or just plain properties) will be shown in the same way. If you intend to do this you should care about cyclic structures and think about how to handle those. Maybe you should remove cycles entirely before outputting as html.
Here is an simple example of a recursive approach with lists:
let object2html = function(obj) {
if(! (obj instanceof Object))
return obj;
return Object.keys(obj).map(key => {
if(obj[key] instanceof Array){
return '<ul>' + obj[key].map(object2html).map(x => '<li>' + x + '</li>').join('') + '</ul>';
}
return key + ' : ' + obj[key];
}).map(toWrap => '<p>' + toWrap + '</p>').join('');
};
Look at this fiddle: https://jsfiddle.net/gqmLf79r/

Print Object like console.log (with a lot of information) in javascript

I need to send an email that contains the console.log output of a JS object. Here a code example:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
console.log(array_multi);
In my console result like this:
Is there some method to get this output in plain text, or should I write a custom parsing function?
If you are using JSON.stringify, you'll get the complete data, however there are a few downsides:
Arrays string properties, functions and other data structures get ignored completely (therefore serializing your data as is won't work¹)
circular references fail to serialize
There is no way to see inheritance from that
In your case you could do:
let array_multi = {};
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
// logs as object
console.log(array_multi);
console.log(typeof array_multi);
// parse and convert to string
console.log(JSON.stringify(array_multi));
console.log(typeof JSON.stringify(array_multi));
In Node.js you've got another option, which is util.format, which will return the same content as a string that you can see in the Node.js console. While it does give you a great insight into the different datatypes and relationships, it cannot show you the same infinite tree that an interactive console is able to show, so it will only show you a small part of the big picture.
¹: Your array_multi should actually be an object, not an array, as arrays should only have numeric keys.
After a lot of search the right method is write a custom function (chrome have once inside dev tools core)
here the solution:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
function print_js_element(elm, show_content = false){
let output_res = "{\n";
let object_keys = Object.keys(elm);
object_keys.some(function(key,index) {
output_res += "\t" + key + ": (" + elm[key].length + ")";
if(show_content){
output_res += " " + JSON.stringify(elm[key]);
}
output_res += "\n";
});
output_res += "\n}";
return output_res;
}
console.log(print_js_element(array_multi,false));
console.log(print_js_element(array_multi,true));
Covert this array into an object first:
let array_multi = [];
array_multi["07:00"] = ["one","two","three"];
array_multi["08:00"] = ["foo","bar","foo"];
array_multi["09:00"] = ["lorem"];
let arrObj = {...array_multi};
console.log(JSON.stringify(arrObj));

Setting JSON Ajax string into variables with Jquery then append an <li>

I have an Ajax script that is currently receiving a JSON data string and appending the data to a <li> on the page, like this:
This is the Jquery script I am using to do this:
jQuery(document).ready(function($) {
$('form.quform').Quform({
successStart: function (response) {
var li = $("<li>").text(JSON.stringify(response));
$("#response").append(li)
But I want to assign variables to the 5 field results and display them in spans so they look something like after I add css to them:
I have tried different things to get this to work, and read a lot of stack articles, One Stack article says to assign the string a variable like this var data = JSON.stringify(myObject, replacer);, but it has not worked. This is the last thing I have tried, but I know it is not right. Any help would be appreciated, thanks.
jQuery(document).ready(function($) {
$('form.quform').Quform({
successStart: function (response) {
var data = JSON.stringify(myObject, replacer);
var content = "balance: " + data.balance + " account_number:" + data.account_number;
var li = $("<li><span>").text(content);
$("#response").parent().append(li);
Also this is the JSON string I receive to the page:
{"type":"success","message":"Your message has been sent, thank you.","record":{"id":108,"bank_name":"Jane Doe","balance":"200","account_number":"8765432187654321","customer_id":"250","monthly":"50"}}
Putting var data = JSON.stringify(myObject, replacer); there doesn't make sense because myObject and replacer are not defined. Don't just copy and paste code. The other answers just provided the general signature of JSON.stringify. You already know how to use it, because you used it in your first code snippet.
Anyways, JSON.stringify converts an existing object/array to a string containing JSON, which also means that response already is an object. So all you have to do is access its properties. In your case,
var data = response.record;
will set data to the correct value.
More info: Access / process (nested) objects, arrays or JSON
Assuming that your response is a JSON response, you would not need to do:
var data= JSON.stringify(myObject, replacer);
Besides, myObject and replacer seem to be undefined. Also, it looks like this line:
var content = "balance: " + data.balance + " account_number:" + data.account_number;
should be:
var content = "balance: " + data.record.balance + " account_number:" + data.record.account_number;
If this does not work then try the following:
var data = $.parseJSON(response);
var content = "balance: " + data.balance + " account_number:" + data.account_number;
This will actually parse the response variable to an object that you can then access through "data.record".

Json string values in javascript

I have following JSON string in a global variable in Javascript
var domains = {
"DomID00001": {
"ID":"DomID00001",
"Name":"Testdomein1"
},
"DomID00002": {
"ID":"DomID00002",
"Name":"Testdomein2"
}
};
What is the best way to retrieve the values from this JSON string and be able to use them in Javascript individually?
If I just alert the domains var it says = [object Object]
Using alert() will not show you objects, this is one of the big advantages of the console. Check this fiddle and use the console (pressing F12 on your browser). Then you understand how to refer to what is inside that object.
var domains = {"DomID00001":{"ID":"DomID00001","Name":"Testdomein1"},"DomID00002":{"ID":"DomID00002","Name":"Testdomein2"}};
console.log(domains);
console.log(domains.DomID00001);
console.log(domains.DomID00001.ID);
Since the keys are variable, you should probably use a for..in loop:
for( domid in domains) if( domains.hasOwnProperty(domid)) {
console.log(domid,domains[domid].ID,domains[domid].Name);
}
Try this:
var domains = {"DomID00001":{"ID":"DomID00001","Name":"Testdomein1"},"DomID00002":{"ID":"DomID00002","Name":"Testdomein2"}};
var strName1 = domains.DomID00001.Name;
var ID1 = domains.DomID00001.ID;
alert('Name: ' + strName1 + ' - ID: ' + ID1);

Loop and get key/value pair for JSON array using jQuery

I'm looking to loop through a JSON array and display the key and value.
It should be a simplified version of the following post, but I don't seem to have the syntax correct: jQuery 'each' loop with JSON array
I also saw the post Get name of key in key/value pair in JSON using jQuery?, but it also seemed like lots of code for a simple activity.
This illustrates what I'm looking for (but it doesn't work):
var result = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
There is no mandatory jQuery requirement, but it is available. I can also restructure the JSON if it cuts down the required code.
You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
//display the key and value pair
alert(k + ' is ' + v);
});
Live demo.
var obj = $.parseJSON(result);
for (var prop in obj) {
alert(prop + " is " + obj[prop]);
}
You can get the values directly in case of one array like this:
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
result['FirstName']; // return 'John'
result['LastName']; // return ''Doe'
result['Email']; // return 'johndoe#johndoe.com'
result['Phone']; // return '123'
The following should work for a JSON returned string. It will also work for an associative array of data.
for (var key in data)
alert(key + ' is ' + data[key]);
Parse the JSON string and you can loop through the keys.
var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"johndoe#johndoe.com","Phone":"123 dead drive"}';
var data = JSON.parse(resultJSON);
for (var key in data)
{
//console.log(key + ' : ' + data[key]);
alert(key + ' --> ' + data[key]);
}
The best and perfect solution for this issue:
I tried the jQuery with the Ajax success responses, but it doesn't work so I invented my own and finally it works!
Click here to see the full solution
var rs = '{"test" : "Got it perfect!","message" : "Got it!"}';
eval("var toObject = "+ rs + ";");
alert(toObject.message);

Categories

Resources