Parse JSON field names and values - javascript

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.

Related

Get JSON attributes using Jquery

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>');
}

how to display multiple json data in html

I am working with weather api, my intention is to display the json data into simple html view....
The problem is that (perhaps) the above script not working at all, even alert, if i am doing it wrong please someone guide....
Script and html
<div id ="fj"></div>
$(document).ready(function() {
var teams;
$.getJSON("http://api.openweathermap.org/data/2.5/forecast/daily?lat=33.5689&lon=72.6378&cnt=10", function(dataDD) {
//do some thing with json or assign global variable to incoming json.
var tasks = $.parseJSON(dataDD.city);
alert(tasks);
//alert('empLoggedId');
$.each(tasks, function(key, value) {
$("#fj").append(data.weather.description);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id="fj"></div>
Any kind of hep or reference will be appreciated
Thanks for your time
Here you go, http://jsfiddle.net/9c2tb8xk/
I am not sure what you are trying to list but I think this is what you want.
$(document).ready(function() {
var teams;
$.getJSON("http://api.openweathermap.org/data/2.5/forecast/daily?lat=33.5689&lon=72.6378&cnt=10", function(dataDD) {
//$.getJson parses for you, dont try to parse it again.
var tasks = dataDD.list //tasks is list property of dataDD
$.each(tasks, function(key, value) { //for each value in list will be in value
$("#fj").append(value.weather[0].description); //I used the value as a specific item from list.
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div id ="fj"></div>

Can't get JSON to render correctly in dropdown

I'm trying to take JSON from a PHP file and use it to populate a dropdown box.
I'm getting the JSON just fine from the PHP file. It looks like this:
[{"state":"AL"},{"state":"AK"},{"state":"AZ"},{"state":"AR"}]
I can see in the response in developer tools that it's coming over fine. However, when I look at the JSON, line 1 is empty and everything is on line 2. Not sure if that's a problem or not.
On the HTML side, here's what I've got:
<select id="myselect"></select>
and
$.getJSON('state_get.php', function(data) {
$.each(data, function(key, val) {
$('#myselect').append("<option>"+key.text+"</option>");
})
});
What I get in my dropdowns are a bunch of options with "undefined". There appear to be one for each JSON value, so something's party right, but not all the way.
Any help would be appreciated.
The first argument to each callback is the index, second is the value also the key to the property is State not text
$.getJSON('state_get.php', function (data) {
$.each(data, function (key, val) {
$('#myselect').append("<option>" + val.state + "</option>");
})
});
First argument of $.each when looping an array is index, the second is the element of the array
Try
$('#myselect').append("<option>"+val.state+"</option>");
Each of the objects in your array would be an element
reference jQuery.each() API Docs
You object has property state, not text
$.each(data, function(key, val) {
$('#myselect').append("<option>" + val.state + "</option>");
});
Try this
$('#myselect').append("<option>"+val.state+"</option>");
Lets have dropdown like below
<select id="myselect" name="stateList" class="state-list ></select>
You can append your value like this
var stateSelector = $('select.state-list');
var option = $("<option value=''></option>");
$.each(data, function(key, val) {
option = $("<option value='" + val.state + "'>" + val.state + "</option>");
stateSelector.append(option);
});
$('.state-list').selectpicker('refresh'); // you can refresh your dropdown if required

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(''));

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