I have created a var and passed JSON data(comma seperated values) to it, but when I want to display json data - it only returns null. Here's the code:
<script type="text/javascript">
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
document.write(data1);
</script>
You can either do it like this:
var data1 = [{order:"145",country:"Dubai",employee:"permanent",customer:"self"} ];
data1.forEach(function(data){
document.write(data.order);
document.write(data.country);
document.write(data.employee);
document.write(data.customer);
});
or you can do it like this
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"}
];
$.each(data1[0], function(key, value){
document.write(key + " " + value);
});
Either way, storing just one object in the list makes this answer a bit redundant unless I show you how to loop over multiple objects.
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
data1.forEach(function(data){
$.each(data, function(key, value){
document.write(key+" "+value);
});
});
I'm using a mix of jQuery here aswell, which might not be optimal but atleast it serves to show that there are multiple ways to accomplishing what you need.
Also, the forEach() method on arrays is a MDN developed method so it might not be crossbrowser compliant, just a heads up!
If you want pure JS this is one of the ways to go
var data1 = [
{order:"145",country:"Dubai",employee:"permanent",customer:"self"},
{order:"212",country:"Abu-Dhabi",employee:"permanent",customer:"Tom"}
];
for(json in data1){
for(objs in data1[json]){
document.write(objs + " : " + data1[json][objs]);
}
}
For simple and quick printing of JSON, one can do something like below and pretty much same goes for objects as well;
var json = {
"title" : "something",
"status" : true,
"socialMedia": [{
"facebook": 'http://facebook.com/something'
}, {
"twitter": 'http://twitter.com/something'
}, {
"flickr": 'http://flickr.com/something'
}, {
"youtube": 'http://youtube.com/something'
}]
};
and now to print on screen, a simple for in loop is enough, but please not e, it won't print array instead will print [object Object]. for simplicity of answer, i won't go in deep to print arrays key and value in screen.
Hope that this will be usefull for someone. Cheers!
for(var i in json) {
document.writeln('<strong>' + i + '</strong>' +json[i] + '<br>');
console.log(i + ' ' + json[i])
}
Related
Related Retrieve two lists, sort and compare values, then display all the results
The question in the related post was how to combine two lists and sort them. The code referenced each item on each list. So, when I got the result, I could manipulate it.
The best solution used console.log(JSON.stringify(result,null,2)); to return the result, nicely combined and sorted.
Trouble for me is being able to translate that back into something I can work with. I can get the result into a variable and display it on the page, but it's the raw output : [ { "Title": "apple", "Type": "rome", "State": null }, ...
Have tried 'JSON.parse(result);' where result is the variable that is used to handle the combination and sorting of the two lists. All that gives is an invalid character error on the line. Also looked at the 'replace' option. That just confused me, tmi. Tried setting a variable directly on the result (so those who know are laughing) 'var foo = result;' That returns object, object.
The desired end result would be to end up with each item separate so I can put them in a table (or a list) on my html page with blanks in any column where there is no data.
I know there has to be a simple, easy way to do this without 200 lines of transformation code. But I can't find a clear example. Everything I'm seeing is for +experts or uses a super simple array that's typed into the code.
Is there a way to attach something like this (from my original) to the result instead of using JSON.stringify? What other step(s) am I missing in being able to extract the fields from JSON.stringify using JSON.parse?
}).success(function (data) {
var title = '';
var type = '';
$.each(data.d.results,
function (key, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
$("#tdtitle").html(title);
$("#tdtype").html(type);
Terry, you wrote: "All that gives is an invalid character error on the line"? Then result is not a valid json. Test it here: http://jsonlint.com/, fix it, then try again.
var data = {
d:{
results: [
{ "Title": "apple", "Type": "rome", "State": null },
{ "Title": "grape", "Type": "fruit", "State": null }
]
}
};
var title = '';
var type = '';
$.each(data.d.results, function (index, value) {
title += "Title: " + value.Title + "<br/>";
type += "Type: " + value.Type + "<br/>";
});
alert(title + type);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Below part of json response, how can i get to objects in rows object, i need to do loop for all id and others attributes. , it is'nt a array so active_chats.rows[1].id not work. Thanks in advance for answers
{
"active_chats":{
"rows":{
"2":{
"id":"2",
"nick":"bart",
"status":"1",
"time":"1453463784",
"user_id":"2",
"hash":"183c12afef48ea9942e5c0a7a263ef441039d832",
"ip":"::1",
"dep_id":"2",
"support_informed":"1",
"has_unread_messages":"1",
"last_user_msg_time":"1453476440",
"last_msg_id":"11",
"wait_time":"5171",
"user_tz_identifier":"Europe/Paris",
"nc_cb_executed":"1",
"user_closed_ts":"1453470674",
"department_name":"ECODEMO"
},
"3":{
"id":"3",
"nick":"robert",
"status":"1",
"time":"1453470058",
"user_id":"2",
"hash":"0fae69094667e452b5401552541602d5c2bd73ef",
"ip":"127.0.0.1",
"dep_id":"2",
"user_status":"1",
"support_informed":"1",
"user_typing":"1453479978",
"user_typing_txt":"Gość opuścił chat!",
"last_msg_id":"10",
"wait_time":"3285",
"user_tz_identifier":"Europe/Paris",
"nc_cb_executed":"1",
"user_closed_ts":"1453479983",
"unanswered_chat":"1",
"department_name":"ECODEMO"
}
},
"size":2
Just do
for (var key in p) {
if (p.hasOwnProperty(key)) {
console.info(key + " => " + p[key]);
}
}
where p is your json response object
did some tests here, your json is invalid.. but if fixed:
for(var row in response.active_chats.rows)
{
for (var key in response.active_chats.rows[row]) {
console.log(key + " => " + response.active_chats.rows[row][key]);
}
}
fiddle example (printing to console)
should do the trick
In order to access the id you would have to do:
var number = 2
var idVal = obj.active_chats.rows[number].id; // idVal = 2
Here obj being whatever variable you saved the JSON in. Looping through the length of active_chats and rows would then help you step through each value.
Also, you can toss your JSON to the text box on this site to get a better picture of what is going on: http://jsbeautifier.org
I have the following code in a display template in sharepoint, I have an array of objects and I need to have the following result.
Name1
Name2
Name3
So I can replace the default rendering of sharepoint multiple people user field with a tooltip.
However, I dont know how to iterate and then concatenate:
Screenshot:
Code:
// List View - Substring Long String Sample
// Muawiyah Shannak , #MuShannak
(function () {
// Create object that have the context information about the field that we want to change it's output render
var projectTeamContext = {};
projectTeamContext.Templates = {};
projectTeamContext.Templates.Fields = {
// Apply the new rendering for Body field on list view
"Project_x0020_Team": { "View": ProjectTeamTemplate }
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(projectTeamContext);
})();
// This function provides the rendering logic
function ProjectTeamTemplate(ctx) {
var projectTeamValue = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];
//newBodyvalue should have the list of all display names and it will be rendered as a tooltip automaticlaly
return "<span title='" + projectTeamValue + "'>" + newBodyValue + "</span>";
}
You can "map" property values from the projectTeamValue array objects into a new array, then "join" those values together (using ", " as the separator in this example) all in one go:
var newBodyValue = projectTeamValue.map(function(person) {
return person.value;
}).join(", ");
If your projectTeamValue array looked like:
[{ value: "Name1" }, { value: "Name2" }, { value: "Name3" }]
Then newBodyValue would be:
"Name1, Name2, Name3"
jsFiddle Demo
Side note: Array.prototype.map() was not available in IE 8 and below but should work in every other browser.
I am returning one JSON response from the server:
{'error':'true',fields:[[{'pk':2,'title':'test'}],{'votes':20,'cant':{1:0,2:3}}]}
Console Dev return
Object { error="true", fields=[2]}
I'm trying to get all the data fields[2], but not work, I'm doing something:
$.each(data.fields, function(i,item){
console.log(data.fields[i]);
})
Question: I know that I'm doing wrong, I want to access all the data in the order fields[2], pk and title.
Thanks.
You can fetch fields[2] using following:
$(data.fields).last()[0] // Give {votes: 20, cant: Object}
which you can use to iterate and get all data as:
var other_data = $(data.fields).last()[0]
$.each(other_data, function(key, value){
console.log('key : ' + key + ' value: ' + value);
});
Your code is need some corrections try this,
Demo
$.each(data.fields[1], function(i,item){
console.log(item);
})
I'm using Sencha Touch (ExtJS) to get a JSON message from the server. The message I receive is this one :
{
"success": true,
"counters": [
{
"counter_name": "dsd",
"counter_type": "sds",
"counter_unit": "sds"
},
{
"counter_name": "gdg",
"counter_type": "dfd",
"counter_unit": "ds"
},
{
"counter_name": "sdsData",
"counter_type": "sds",
"counter_unit": " dd "
},
{
"counter_name": "Stoc final",
"counter_type": "number ",
"counter_unit": "litri "
},
{
"counter_name": "Consum GPL",
"counter_type": "number ",
"counter_unit": "litri "
},
{
"counter_name": "sdg",
"counter_type": "dfg",
"counter_unit": "gfgd"
},
{
"counter_name": "dfgd",
"counter_type": "fgf",
"counter_unit": "liggtggggri "
},
{
"counter_name": "fgd",
"counter_type": "dfg",
"counter_unit": "kwfgf "
},
{
"counter_name": "dfg",
"counter_type": "dfg",
"counter_unit": "dg"
},
{
"counter_name": "gd",
"counter_type": "dfg",
"counter_unit": "dfg"
}
]
}
My problem is that I can't parse this JSON object so that i can use each of the counter objects.
I'm trying to acomplish that like this :
var jsonData = Ext.util.JSON.decode(myMessage);
for (var counter in jsonData.counters) {
console.log(counter.counter_name);
}
What am i doing wrong ?
Thank you!
Javascript has a built in JSON parse for strings, which I think is what you have:
var myObject = JSON.parse("my json string");
to use this with your example would be:
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
Here is a working example
EDIT: There is a mistake in your use of for loop (I missed this on my first read, credit to #Evert for the spot). using a for-in loop will set the var to be the property name of the current loop, not the actual data. See my updated loop above for correct usage
IMPORTANT: the JSON.parse method wont work in old old browsers - so if you plan to make your website available through some sort of time bending internet connection, this could be a problem! If you really are interested though, here is a support chart (which ticks all my boxes).
In a for-in-loop the running variable holds the property name, not the property value.
for (var counter in jsonData.counters) {
console.log(jsonData.counters[counter].counter_name);
}
But as counters is an Array, you have to use a normal for-loop:
for (var i=0; i<jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
This is my answer:
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p>
First Name: <span id="fname"></span><br>
Last Name: <span id="lname"></span><br>
</p>
<script>
var txt =
'{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
//var jsonData = eval ("(" + txt + ")");
var jsonData = JSON.parse(txt);
for (var i = 0; i < jsonData.employees.length; i++) {
var counter = jsonData.employees[i];
//console.log(counter.counter_name);
alert(counter.firstName);
}
</script>
</body>
</html>
Just as a heads up...
var data = JSON.parse(responseBody);
has been deprecated.
Postman Learning Center now suggests
var jsonData = pm.response.json();
Something more to the point for me..
var jsontext = '{"firstname":"Jesper","surname":"Aaberg","phone":["555-0100","555-0120"]}';
var contact = JSON.parse(jsontext);
document.write(contact.surname + ", " + contact.firstname);
document.write(contact.phone[1]);
// Output:
// Aaberg, Jesper
// 555-0100
Reference:
https://learn.microsoft.com/en-us/scripting/javascript/reference/json-parse-function-javascript
"Sencha way" for interacting with server data is setting up an Ext.data.Store proxied by a Ext.data.proxy.Proxy (in this case Ext.data.proxy.Ajax) furnished with a Ext.data.reader.Json (for JSON-encoded data, there are other readers available as well). For writing data back to the server there's a Ext.data.writer.Writers of several kinds.
Here's an example of a setup like that:
var store = Ext.create('Ext.data.Store', {
fields: [
'counter_name',
'counter_type',
'counter_unit'
],
proxy: {
type: 'ajax',
url: 'data1.json',
reader: {
type: 'json',
idProperty: 'counter_name',
rootProperty: 'counters'
}
}
});
data1.json in this example (also available in this fiddle) contains your data verbatim. idProperty: 'counter_name' is probably optional in this case but usually points at primary key attribute. rootProperty: 'counters' specifies which property contains array of data items.
With a store setup this way you can re-read data from the server by calling store.load(). You can also wire the store to any Sencha Touch appropriate UI components like grids, lists or forms.
This works like charm!
So I edited the code as per my requirement. And here are the changes:
It will save the id number from the response into the environment variable.
var jsonData = JSON.parse(responseBody);
for (var i = 0; i < jsonData.data.length; i++)
{
var counter = jsonData.data[i];
postman.setEnvironmentVariable("schID", counter.id);
}
The answer with the higher vote has a mistake. when I used it I find out it in line 3 :
var counter = jsonData.counters[i];
I changed it to :
var counter = jsonData[i].counters;
and it worked for me.
There is a difference to the other answers in line 3:
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData[i].counters;
console.log(counter.counter_name);
}
You should use a datastore and proxy in ExtJs. There are plenty of examples of this, and the JSON reader automatically parses the JSON message into the model you specified.
There is no need to use basic Javascript when using ExtJs, everything is different, you should use the ExtJs ways to get everything right. Read there documentation carefully, it's good.
By the way, these examples also hold for Sencha Touch (especially v2), which is based on the same core functions as ExtJs.
Not sure if my data matched exactly but I had an array of arrays of JSON objects, that got exported from jQuery FormBuilder when using pages.
Hopefully my answer can help anyone who stumbles onto this question looking for an answer to a problem similar to what I had.
The data looked somewhat like this:
var allData =
[
[
{
"type":"text",
"label":"Text Field"
},
{
"type":"text",
"label":"Text Field"
}
],
[
{
"type":"text",
"label":"Text Field"
},
{
"type":"text",
"label":"Text Field"
}
]
]
What I did to parse this was to simply do the following:
JSON.parse("["+allData.toString()+"]")