Get JSON attributes using Jquery - javascript

This is my test.json file :
[{"id":"12","url":"http:\/\/localhost\/test\/1\/images\/pic\/3.jpg"},
{"id":"11","url":"http:\/\/localhost\/test\/1\/images\/pic\/1.png"},
{"id":"10","url":"http:\/\/localhost\/test\/1\/images\/pic\/2.png"}]
I want to print it on emphasized text using jQuery.
<div>12<img src="http://localhost/test/1/images/pic/3jpg" /></div>
<div>11<img src="http://localhost/test/1/images/pic/1jpg" /></div>
<div>10<img src="http://localhost/test/1/images/pic/2jpg" /></div>

If you want to get your json from the server rather than hard-coding it into your javascript, use jquery's .getJSON() method (see docs). Then iterate over the response data using the .each() method (see docs).
$.getJSON(
'test.json',
function(data) {
$.each(data, function(i, obj) {
el = $('<div>' + obj['id'] + '<img src="'+ obj['url'] +'" /></div>');
$('body').append(el);
});
}
);

Check the valid JSON bellow and try to reformat yours like it, you can find also example that show you how you can parse a JSON Object using for in to acheive the desired result.
Hope this helps.
var test_json =
[
{"id":"12","url":"http:\/\/localhost\/test\/1\/images\/pic\/3.jpg"},
{"id":"11","url":"http:\/\/localhost\/test\/1\/images\/pic\/1.png"},
{"id":"10","url":"http:\/\/localhost\/test\/1\/images\/pic\/2.png"}
];
for ( var key in test_json )
{
console.log('<div>'+test_json[key].id+'<img src="'+test_json[key].url+'" /></div>');
}

Related

Append data in JSON format

I have some data in JSON format. I want to display it on a div. Following doesn't work. Any idea where i should change.
<div class="risktable"> </div>
$.ajax({
contentType:'application/json',
data: {"sprint_start":"2015-12-13","sprint_end":"N.A.","available":[{"id":5,"name":"Thisun H","free_time":0.0,"possible":[]}],"assigns":[{"assignee_id":6,"assigned_to":"Isuru P","status":"OnTrack","hours_per_sprint":6,"limit_per_sprint":6.0,"limit_per_day":6.0,"tasks":[{"task_id":3,"task_name":"Schedule Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Isuru P","estimated_time":6,"remaining_time":6,"completed_ratio":0,"start_date":"2015-12-10","due_date":"2015-12-13","critical_task":true,"dependents":[]}]},{"assignee_id":7,"assigned_to":"Manoj D","status":"Risk","hours_per_sprint":6,"limit_per_sprint":5.0,"limit_per_day":5.0,"tasks":[{"task_id":4,"task_name":"Resource Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Manoj D","estimated_time":6,"remaining_time":0,"completed_ratio":0,"start_date":"2015-12-10","due_date":"2015-12-13","critical_task":true,"dependents":[]}]},{"assignee_id":5,"assigned_to":"Thisun H","status":"OnTrack","hours_per_sprint":0,"limit_per_sprint":6.0,"limit_per_day":6.0,"tasks":[{"task_id":1,"task_name":"Redmine Connection","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Thisun H","estimated_time":3,"remaining_time":0,"completed_ratio":100,"start_date":"2015-12-07","due_date":"2015-12-09","critical_task":true,"dependents":[2,3,4]},{"task_id":2,"task_name":"Risk Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Thisun H","estimated_time":10,"remaining_time":0,"completed_ratio":100,"start_date":"2015-12-10","due_date":"2015-12-12","critical_task":false,"dependents":[]}]}],"suggestions":[{"dev_id":5,"dev_name":"Thisun H","task_id":4,"task_name":"Resource Servlet"}]},
success: function(data){
$.each(data.data, function(i,value) {
$('.risktable').append(
'<div>'+'<p>'+ value.assigns.assignee_id + '</p>'
+'</div>'
);
});
}
});
assigns property on your json object is an array. you need to loop through the items in that and build your div and append that.
$.each(data.assigns, function(i,value) {
var item='<div>'+'<p>'+ value.assignee_id + '</p></div>';
$('.risktable').append(item);
});
Here is a working sample.
If the json data you have isn't being fetched externally (i.e. you have the json object definition & value already), there's no need to do the ajax method call. Ajax is used for making external requests.
Alternatively, you could store your json object as a generic variable and parse through it (assuming you are using jQuery) like the following.
var mock_data = {"sprint_start": "2015-12-13","sprint_end":"N.A.","available": [{"id":5,"name":"Thisun H","free_time":0.0,"possible":[]}],"assigns":[{"assignee_id":6,"assigned_to":"Isuru P","status":"OnTrack","hours_per_sprint":6,"limit_per_sprint":6.0,"limit_per_day":6.0,"tasks":[{"task_id":3,"task_name":"Schedule Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Isuru P","estimated_time":6,"remaining_time":6,"completed_ratio":0,"start_date":"2015-12-10","due_date":"2015-12-13","critical_task":true,"dependents":[]}]},{"assignee_id":7,"assigned_to":"Manoj D","status":"Risk","hours_per_sprint":6,"limit_per_sprint":5.0,"limit_per_day":5.0,"tasks":[{"task_id":4,"task_name":"Resource Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Manoj D","estimated_time":6,"remaining_time":0,"completed_ratio":0,"start_date":"2015-12-10","due_date":"2015-12-13","critical_task":true,"dependents":[]}]},{"assignee_id":5,"assigned_to":"Thisun H","status":"OnTrack","hours_per_sprint":0,"limit_per_sprint":6.0,"limit_per_day":6.0,"tasks":[{"task_id":1,"task_name":"Redmine Connection","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Thisun H","estimated_time":3,"remaining_time":0,"completed_ratio":100,"start_date":"2015-12-07","due_date":"2015-12-09","critical_task":true,"dependents":[2,3,4]},{"task_id":2,"task_name":"Risk Servlet","project_id":1,"sprint_id":"2015-12-13","parent_id":0,"status":"New","assigned_to":"Thisun H","estimated_time":10,"remaining_time":0,"completed_ratio":100,"start_date":"2015-12-10","due_date":"2015-12-12","critical_task":false,"dependents":[]}]}],"suggestions":[{"dev_id":5,"dev_name":"Thisun H","task_id":4,"task_name":"Resource Servlet"}]};
$(mock_data.assigns).each( function(){
$('.risktable').append('<div><p>'+this.assignee_id+'</p></div>');
});
You can see the sample here:
http://codepen.io/team/anthro-web/pen/yeYobN

jquery - separate JSON and HTML from AJAX Response

I have a AJAX response something like this.
[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌​464"}]<table id="table"></table>
It has both JSON and HTML in the response.
I wanted to separate those two things.
And use the JSON for a chart function I've created.
And then append that table to a div.
Any suggestions will be very much fruitful.
Thanks in advance.
In php
$array = 'Your json array';
$html = 'Your html codes';
Make a single array with two keys
$newArray = array();
$newArray['json'] = $array;
$newArray['html'] = $html;
echo json_encode($newArray);
In Jquery
DataType: 'JSON',
success:function(response){
response.json = 'This is your json';
response.html = 'This is your html';
}
Add the HTML to the JSON response and use it like you would your other values (make sure to escape your html). Also use JSONLint to make sure your JSON is valid.
[
{
"label": "label",
"label1": "67041",
"label2": "745",
"label3": "45191",
"label4": "11‌​464",
"html": "<table id=\"table\"></table>"
}
]
While I recommend you not to do that, because is to geeky and hard to maintain, You can solve id by detecting the JSON object using regex, like this:
var data = '[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌464"}]<table id="table"></table>';
var json_pattr = /\[.*\]/g;
var json_str = json_pattr.exec(data)[0];
var json_data = eval( '(' + json_str.substr(1, json_str.length-2) + ')') ;
var html_pattr = /\}\].*/g;
var html_text = html_pattr.exec(data)[0];
var html_data = html_text.substr(2);
//json_data = [object] {"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌464"}
//html_data = [text] <table id="table"></table>
The Best Solution would be to use a template engine like jquery templates to define your html, and then get your data via $.json and evaluate it agains your desired template already on the client, no need to be sending it right along with your data and be doing that kind of processing in run time.
JavaScript
// assuming you keep receiving this
var data =
'[{"label":"label","label1":"67041","label2":"745","label3":"45191","label4":"11‌464"},'
+'{"label":"label2","label1":"0000","label2":"222","label3":"333","label4":"11‌333"}]'
+'<table id="table"></table>';
// parse the data with regex
var json_pattr = /\[.*\]/g;
var json_str = json_pattr.exec(data)[0];
var json_data = eval( '(' + json_str + ')') ;
var html_pattr = /\}\].*/g;
var html_text = html_pattr.exec(data)[0];
var html_data = html_text.substr(2);
//json_data = [object] {"label":"label","label1": ...
//html_data = [text] <table id="table"></table> ...
// then use jquery templates to render it
var data = json_data;
$('body').append(html_data);
$('#trTemplate').tmpl(data).appendTo('#table');
HTML
<script id="trTemplate" type="text/x-jquery-tmpl">
<tr>
<td>${label}</td>
<td>${label1}</td>
<td>${label2}</td>
<td>${label3}</td>
<td>${label4}</td>
</tr>
</script>
CSS
#table, td{ border:1px solid #000; padding:5px; }
Here is an working JSFiddle example for you to test it.
Note how this works when you have more than one {json object, it's creates more lines in the table :) }
If you use jquery templates only, and now assuming that you can actually modify your output than the best thing to do is:
New JavaScript Version of Code with template only and no HTML on 'data'
$.json('http://server.com/url/service/someservice.something', function(data){
$('body').append(<table id="#table></table>");
$('#trTemplate').tmpl(data).appendTo('#table');
})
Much more simple don't you think?! Hope this helps guiding you on the right path.
Link to jquery tmpl: http://knockoutjs.com/downloads/jquery.tmpl.min.js.
Although after understanding my example, if you are building a system to scale on, and you are not just doing a simple widget app, I would recommend you to check something more robust in terms of functionalities and support like Knockoutjs as jquery tmpl has been deprecated, unfortunately.

jQuery .each() prints only last value from json

I have an issue with jQuery.each(). I retrieve json data from another php file then I want to print specific key from it.
here is the js :
<div class="row" id="fetchmember">
<script type="text/javascript">
jQuery('#group').change(function() {
var id_group = this.value;
var memberjson = "fetchmember.php?group="+id_group;
jQuery.getJSON(memberjson,function(data){
jQuery.each(data, function(i, item) {
jQuery("#fetchmember").empty().append("<li>"+item.name+"</li>");
});
});
});
</script>
</div>
JSON result from one of the selected option :
[{"id":"1645819602","name":"Michael Great","first_name":"Michael","last_name":"Great"},
{"id":"100000251643877","name":"George Pambudi","first_name":"George","last_name":"Pambudi"}]
I want to print all of name from the json, but it print only last name key of the json. I have tried to use .html() and it also returns only last name key. What's wrong with my code?
Any advice and helps would be greatly appreciated. Thank you very much
You are emptying the div first and then appending :
jQuery("#fetchmember").empty().append("<li>"+item.name+"</li>");
Instead just use :
jQuery("#fetchmember").append("<li>"+item.name+"</li>");
Don't empty it in the loop if you don't want to keep only the last data. Change your callback to
jQuery("#fetchmember").empty();
jQuery.each(data, function(i, item) {
jQuery("#fetchmember").append("<li>"+item.name+"</li>");
});
Note that you can make one append if you want :
jQuery("#fetchmember").html(data.map(function(item){
return '<li>'+item.name+'</li>'
}).join(''));

Parse JSON field names and values

I've looked half a day for a solution to this, but nothing seems to work. I want to use jQuery to load JSON from a file that essentially looks like this:
[{"field_a":"1","field_b":"1000","field_c":"PRINCIPAL CASH"},
{"field_a":"2","field_b":"2000","field_c":"TRUST ASSETS"},
{"field_a":"3","field_b":"3000","field_c":" BONDS"},
{"field_a":"4","field_b":"4000","field_c":" STOCKS"}]
What I want to do is parse the JSON to dynamically populate input fields, so something like (please note that ??field?? and ??field value?? is what I need to know):
<input id="field_a" name="field_a" value="">
<input id="field_b" name="field_b" value="">
<input id="field_c" name="field_c" value="">
<script type="text/javascript">
$(function(){
//GET THE JSON DATA
$.getJSON('../coreScripts/selectGeneralLedger.php', function(data) {
//PARSE TO FIELDS
$.each(data, function(index) {
$("#"+data[index].??field name??).attr("value", data[index].??field value??);
}) //END PARSE
}); //End get JSON
});
</script>
I know how to access the field values manually using data[index].field_a, but can't for the life of me figure out how to parse this dynamically. Any help would be appreciated.
UPDATE*
adeneo gave me the solution below in the comments. Simple. Here's the script:
var data = [{"field_a":"1","field_b":"1000","field_c":"PRINCIPAL CASH"}, {"field_a":"2","field_b":"2000","field_c":"TRUST ASSETS"}, {"field_a":"3","field_b":"3000","field_c":" BONDS"}, {"field_a":"4","field_b":"4000","field_c":" STOCKS"}];
$.each(data, function(index, obj) {
$.each(obj, function(key, value) {
$('<input />', {id: key, name:key, value:value}).appendTo('body');
});
});
If i'm not understand you, it can be an answer.
$.each(data, function(index) {
$.each(data[index] ,function(key,value){
console.log("key :" + key + " value :" + value );
})
}) //END PARSE
key variable is the answer what you request for.

Show enter contents of JSON

QUESTION ::
I know this is a redundant question, but I am finding little help in other similar questions...
I have a json file.
I can load the json fine, but when I try to output a specific element with this
div.innerHTML = jsonfromfile[element];
I only get this...
[object Object]
as my output...
How do I get the entire element to display instead of this [object Object]?
more code to get a feel for how it is being done up...
var activity;
function jsfr() {
$.getJSON('myjson.json', function(response){
jsonfromfile = response;
})
}
.
.
.
SOLUTION :: from Francis Stalin's answer
I added a new function...
var items;
function outty(data) {
$.each(data, function(key, val) {
items=items+key+","+val+";";
});
}
and i set the depth on the json leaving me with an object which i send to outty...
dpth = jsonfromfile["elementOne"]["elSubone"]["elsuboneSub"];
outty(dpth);
div.innerHTML=items;
here's the HTML that shows the div it all prints to...
<div class="col-rght">
<div class="text" id="postcomp"></div>
</div> <!--div class="col-rght"-->
this turns the object of your desired json depth into an ugly string that you can then format for display..
if you like html lists check out how Stalin did it, but be weary of his appendTo('div')... this will place your list in every div. Try putting the name of the class of the div you want to print to with a period leading it, appendTo('.outputbox')
you can't append the json object directly into ur html. u have to parse and convert into string
$.getJSON('myjson.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('div');
});
http://api.jquery.com/jQuery.getJSON/
Use JSON.stringify(yourjsonobjecthere)
Try div.innerHTML = JSON.stringify(jsonfromfile[element]);

Categories

Resources