var test=[];
$(document).ready(function(){
$.getJSON("data.json",function(data){
$.each(data,function(key,value){
test.push(value.topic);
});
});
});
Here is my javacript code. I want to push json object's all values with key as topic. But when I try to access test[i] (i be any integer within array length) I get an error "undefined" . What' am I msissing?
Here is my json object sample-
[
{
"topic": "Books",
"quantity": 3
},
{
"topic": "Grossery",
"quantity": 3
},
{
"topic": "stationery",
"quantity": 3
},
{
"topic": "food",
"quantity": 2
},
{
"topic": "market items",
"quantity": 3
}
]
See the following working code:
var data = [
{
"topic": "Books",
"quantity": 3
},
{
"topic": "Grossery",
"quantity": 3
},
{
"topic": "stationery",
"quantity": 3
},
{
"topic": "food",
"quantity": 2
},
{
"topic": "market items",
"quantity": 3
}
]
var test = [];
$.each(data,(i,v) => test.push(v.topic));
console.log(test);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
Your code seems to be working fine for me.
Are you accessing the data before the callback that you pass to getJson has been executed?
Here's an example that works if I serve it locally using python3 -m http.server 8080:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
var test=[];
$(document).ready(function(){
$.getJSON("data.json",function(data){
$.each(data,function(key,value){
test.push(value.topic);
});
// only use test array after data has been loaded
doWork();
});
});
function doWork() {
$('#output').text(
test + ' ' + test[0]
);
}
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>
Related
I am using txt.general_1.value in template to display its value but it shows error in console Can't find txt.general_1.value in [object Object]
But if I just use txt in template, it displays [object Object]
Following is the code. Kindly help me in resolving this issue.
Please note that following code is just to reproduce the problem, actual data is different.
<script>
var json_obj =
{
"all": [
{
"row": "row",
"column": "col-md-6",
"txt": {
"general_1": {
"type": "a",
"value": "aaa - Hello world"
},
"general_2": {
"type": "b",
"value": "bbb - Hello world"
},
"general_3": {
"type": "c",
"value": "ccc - Hello world"
}
}
}
]
};
var data = json_obj['all'][0];
var template = "<div class=\"{{row}}\"><p class=\"{{column}}\">{{txt.general_1.value}}</p></div>";
var text = Mustache.render(template, data);
$('#target').html(text);
</script>
I tried to reproduce the problem in the code snippet but didn't see any issue. The value is rendered correctly. Check the json_obj in your app, maybe it doesn't always contain the txt.general_1.value properties.
var json_obj = {
"all": [{
"row": "row",
"column": "col-md-6",
"txt": {
"general_1": {
"type": "a",
"value": "aaa - Hello world"
},
"general_2": {
"type": "b",
"value": "bbb - Hello world"
},
"general_3": {
"type": "c",
"value": "ccc - Hello world"
}
}
}]
};
var data = json_obj['all'][0];
var template = "<div class=\"{{row}}\"><p class=\"{{column}}\">{{txt.general_1.value}}</p></div>";
var text = Mustache.render(template, data);
$('#target').html(text);
<script src="https://unpkg.com/mustache#latest"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="target"></div>
I am currently trying to send a user information about a JSON object that I've recieved from an API. An example of the format is
[
{
"lang_code": "eng",
"site_language": "1",
"name": "English"
},
{
"lang_code": "afr",
"site_language": "1",
"name": "Afrikaans"
},
{
"lang_code": "ale",
"site_language": "0",
"name": "Aleut"
},
]
I want to be able to access the lang_code property of every single language and send it. I've tried to use
var languageCodes;
var languageResult = body.lang_code; //body is the result from a request.get({ ... })
for(var codes in languageResult) {
languageCodes = languageResult[codes];
}
Object.keys does nothing, as it just sends 72 numbers to me. Any thoughts?
On a side note, I also want people to be able to type "! languages [my command] eng", for example, and it sends "English" instead of just sending "1 is [object Object]".
Assuming body is the array at the top of your question, if you just want an array of all the language codes, this should suffice
var languageCodes = body.map(function(lang) {
return lang.lang_code;
});
var body = [{
"lang_code": "eng",
"site_language": "1",
"name": "English"
}, {
"lang_code": "afr",
"site_language": "1",
"name": "Afrikaans"
}, {
"lang_code": "ale",
"site_language": "0",
"name": "Aleut"
}];
var languageCodes = body.map(function(lang) {
return lang.lang_code;
});
document.getElementById('out').innerHTML = JSON.stringify(languageCodes);
<pre id="out"></pre>
I looped through your lang_codes like this:
var codes = [{"lang_code":"eng","site_language":"1","name":"English"}, {"lang_code":"afr","site_language":"1","name":"Afrikaans"},{"lang_code":"ale","site_language":"0","name":"Aleut"}];
for(var i = 0; i < codes.length; i++) {
console.log(codes[i].lang_code);
}
I am working on this demo. Why am I not able to query the JSON object by using the jsonSelect plugin?
var jsonData = {
"name": {
"first": "Lloyd",
"last": "Hilaiel"
},
"favoriteColor": "yellow",
"languagesSpoken": [{
"language": "Bulgarian",
"level": 2
}, {
"language": "English",
"level": 1
}, {
"language": "Spanish",
"level": 7
}]
};
var selector = '.name > *';
JSONSelect.forEach(selector, jsonData, function (resultObj) {
$('body').append('<p>' + $.trim(JSON.stringify(resultObj, null, ' ')) + '</p>');
});
You cannot directly include the JS file from Github. You need to host it yourself or find a CDN.
I need to print this information when clicking a button and sorting if by date, so far i have this: I have json file that looks like this, but I haven't been able to print it on the page and still haven't got to the sorting by date part. I am not sure if the problem is the link to the ajax version i am using or what is the problem, because i saw an example that looks just like this on youtube and it works just fine.
JSON:
[
{
"users": [
{
"name": "user1",
"Endorsement": "some comment",
"date": "8/11/2012"
},
{
"name": "user2",
"Endorsement": "some comment2",
"date": "9/27/11"
},
{
"name": "user3",
"Endorsement": "some comment3"
},
{
"name": "user4",
"Endorsement": "some comment4",
"date": "4/2/13"
},
{
"name": "user5",
"Endorsement": "some comment5"
},
{
"name": "user6",
"Endorsement": "some comment6",
"date": "3/17/13"
},
{
"name": "user7",
"Endorsement": "some comment7",
"date": "5/22/13"
},
{
"name": "user8",
"Endorsement": "some comment8",
"date": "9/27/13"
}
]
}
]
HTML updated:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Contact</title>
<link rel="shortcut icon" href="stridesFavicon.ico">
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap-responsive.css">
<link rel="shortcut icon" href='http://sites.google.com/site/lowcoupling/favicon_16x16.ico' />
</head>
<body>
<!--Body content-->
<div id='Div1'>
Get JSON Data
</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<script src="myscript.js" type="text/javascript" /></script>
<script type="text/javascript">
$(document).ready(function () {
$('.dropdown-toggle').dropdown();
});
</script>
</body>
</html>
JS updated:
$("#clickme").click(function () {
$.getJSON("users.json", function (data) {
var items = [];
$.each(data, function (key, dvalue) {
$.each(dvalue, function (key, value) {
items.push('<li id="' + key + '">' + value + '</li>');
});
});
$('<ul/>', {
'class': 'interest-list',
html: items.join('')
}).appendTo('body');
});
});
But is not working. meaning is not loading user names; instead it is printing something like this every time i click the link:
•[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
the jason is missing some commas, every line inside the json should end with a comma unless it is the last child in the scope, which makes it:
[
{
"users": [
{
"name": "user1",
"Endorsement": "some comment",
"date": "8/11/2012"
},
{
"name": "user2",
"Endorsement": "some comment2",
"date": "9/27/11"
},
{
"name": "user3",
"Endorsement": "some comment3"
},
{
"name": "user4",
"Endorsement": "some comment4",
"date": "4/2/13"
},
{
"name": "user5",
"Endorsement": "some comment5"
},
{
"name": "user6",
"Endorsement": "some comment6",
"date": "3/17/13"
},
{
"name": "user7",
"Endorsement": "some comment7",
"date": "5/22/13"
},
{
"name": "user8",
"Endorsement": "some comment8",
"date": "9/27/3"
}
]
}
]
try !
$("button").click(function () {
$.getJSON("users.json", function (obj) {
$.each(obj.users, function (key, value) {
$("ul").append("<li>" + value.name + "</li>");
});
});
});
and if there is error then use debug console in browser.
and either make a fiddle or write what is error. and there seems no ul element in your html.
The json is not valid. I validated using http://jsonlint.com/ and it says error at line 6. You left a comma in below part:
"Endorsement": "some comment"
"date":"8/11/2012"
This is the first endorsement-date pair
$("button").click(function () {
$.getJSON("users.json", function (data) {
for (i in data)
{
for (k in data[i]) {
alert(data[i][k]);
}
});
});
$.ajax({
type:'POST',
url:'Default.aspx/GetPro',
data:"{Pid:'"+ faram+"'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
cache: false,
success: function(msg) {
alert("{Pid:'"+ faram+"'}");
var orders =msg;
if (orders.length > 0) {
test(orders);
}
else {
alert("No Record Found");
}
},
error: function(xhr, textStatus, errorThrown) {
alert(xhr.status);
alert(errorThrown);
alert(xhr.responseText);
}
});
function test(data)
{
for (i in data)
{
//ProductName Is Property Field Of c# Object
alert(data[i]['ProductName'])
}
}
I know that I can create this JSON:
[
{
"Title": "Something",
"Price": "234",
"Product_Type": "dsf sf"
},
{
"Title": "hskiuea",
"Price": "4234",
"Product_Type": "sdawer"
}
]
*It uses the values obtained from text inputs contained within an element with the class "newpappend" - As shown below
Using the following code which obtains values from my HTML:
var jsonObj = []; //declare array
$(".newpappened").each(function () {
var p_title = $(this).find('#p_title').val();
var p_price = $(this).find('#p_price').val();
var p_ptype = $(this).find('#p_ptype').val();
jsonObj.push({Title: p_title, Price: p_price, Product_Type: p_ptype});
$(this).remove();
});
But, my goal is to end up with the JSON structured like this:
{
"Product_List": {
"Product": [
{
"Title": "asdf",
"Price": "53",
"Product_Type": "Adfsdf"
},
{
"Title": "asgsd",
"Price": "123",
"Product_Type": "Ntohig"
}
]
}
}
Basically, I am struggling with the correct Javascript to use to reach my goal
You are really close. Start with what you have, and then later:
var output = {
"Product_List": {
"Product": jsonObj
}
}
// output is now what you are looking for.