Javascript (Ajax) Parse JSON value - javascript

total javascript noob here. Just trying to get an understanding for the language.
I'm requesting a JSON request using the following code:
function request(){
$.ajax({
dataType: "jsonp",
type: 'GET',
url: "getWebsite",
success: function(result){
data = result;
$('.data').text(data);
console.log(data);
}});
The get request returns something like this:
"items": [
{
"topLevelComment": {
"authorDisplayName": "a"
"textDisplay": "b"
},
{
"topLevelComment": {
"authorDisplayName": "c"
"textDisplay": "d"
}
I would like to cycle through the AuthorDisplayName and textDisplay and randomly pick one from each. The best way to do this would probably be to put them both into arrays if I had to guess. I'm not sure how to even go about this.

var json={
"items": [{
"topLevelComment": {
"authorDisplayName": "a",
"textDisplay": "b"
}
}, {
"topLevelComment": {
"authorDisplayName": "c",
"textDisplay": "d"
}
}, {
"topLevelComment": {
"authorDisplayName": "e",
"textDisplay": "f"
}
}, {
"topLevelComment": {
"authorDisplayName": "g",
"textDisplay": "h"
}
}]
};
$("input:button").on("click",function(){
selectRand = Math.floor((Math.random() * json.items.length))
var r=json.items[selectRand].topLevelComment.textDisplay;
console.log(r);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="selectRand"/>

If your data is already in Object format, and you only want to get one from random pick. Then you don't have to loop for all the data. Just randomly select one index from your total data.
function request(){
$.ajax({
dataType: "jsonp",
type: 'GET',
url: "getWebsite",
success: function(result){
data = result;
$('.data').text(data);
console.log(data);
var randomIndex = Math.floor((Math.random() * data.items.length));
console.log("Selected data authorDisplayName: " + data.items[randomIndex].topLevelComment.authorDisplayName);
console.log("Selected data textDisplay: " + data.items[randomIndex].topLevelComment.textDisplay);
}
});
}

items is already an array. So you do the following:
Parse the result to json (Only if a string is returned)
items = JSON.parse(items)
Get a random index
let index = Math.floor((Math.random() * items.length))
Get the random data
let authorDisplayName = items[index].topLevelComment.authorDisplayName
let textDisplay = items[index].topLevelComment.textDisplay

As far as i understood you are trying to display a random object from the items array?
The items variable is already an array, so you don't need to create one. To get a random element of the array you can use the following code:
var item = result.items[Math.floor(Math.random()*items.length)];
I'm not sure where exactly the items array is located, let's say it's on the root of the result. You will probably also need to run the array through the method JSON.parse() to make it a valid JavaScript object.
And then to get the text and display name you can do this:
var authour = item.topLevelComment.authorDisplayName;
var text = item.topLevelComment.textDisplay;

Related

Use a unicode string in JSON file as function parameter

I'm using the answer from this question to create random characters:
String.fromCharCode(0x30A0 + Math.random() * (0x30FF - 0x30A0 + 1));
I created a function with the same principle so I can change the first and the last character of the range:
function uni_char(first, last) {
var char = String.fromCharCode(first + Math.random() * (last - first + 1))
return char;
}
For example, if I run the function with 0x0000 and 0x007F as parameters, it works as expected. What I'm trying to do is to read a JSON file with multiple character ranges to use them with the function. This is the JSON:
[
{
"first": "0x0000",
"last": "0x007F"
},
{
"first": "0x0080",
"last": "0x00FF"
}
]
I populate an array with the JSON file data using the answer from this question:
var blocks = [];
$.ajax({
async: false,
url: '/scripts/data/blocks.json',
data: "",
accepts:'application/json',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
blocks.push(data[i]);
}
}
});
But when I use the values from the array with the function:
uni_char(blocks[0].first, blocks[0].last);
It just creates a � symbol. What am I missing? Maybe an encoding problem? Or a logic problem?

AJAX JSON response is returning the correct values, but also undefined values in between?

I'm working on some JavaScript code that is going to find the smallest unused number in a specified range of numbers. The AJAX request gathers all used numbers in the specified range, but is additionally returning undefined values in between the correct values? I've compared the returned values from the JSON response to what's currently in the SQL table and all the correct values are in both the JSON response and the SQL table, so I'm not sure where the undefined values are coming from.
https://imgur.com/a/rXLfEJk
JavaScript:
//Specified range of numbers to search.
var startRange = 40000;
var endRange = 49999;
//UPC's are padded with to 13 digits with 0's then sent as parameters.
var startUPC = '00000000' + startRange;
var endUPC = '00000000' + endRange;
// AJAX call to web API that gathers all UPC's within a range.
$.ajax({
url: "api/GetNewPLU",
type: "GET",
dataType: "json",
data: { 'startUPC': startUPC, 'endUPC': endUPC },
success: function (data) {
$.each(data.data, function (i, UPCs) {
for (var i in UPCs) {
console.log("UPC: " + UPCs[i].F01);
}
})
},
error: function (error) {
console.log(`Error ${error}`)
}
})
JSON Response:
{
"draw": null,
"data": [{
"DT_RowId": "row_0000000040002",
"OBJ_TAB": {
"F01": "0000000040002"
}
}, {
"DT_RowId": "row_0000000040008",
"OBJ_TAB": {
"F01": "0000000040008"
}
}, {
"DT_RowId": "row_0000000040013",
"OBJ_TAB": {
"F01": "0000000040013"
}
}, {
"DT_RowId": "row_0000000040017",
"OBJ_TAB": {
"F01": "0000000040017"
}
}
}
I plan to loop through the used numbers from the AJAX request comparing them to a sequentially incremented generated number until there is not a match and then save that unused number. I'm not sure if it's worth figuring out why I'm returning both values and undefined or if I should just find a way to filter out the undefined.
lodash _.difference can help to you.
Create two arrays. One for generated values, one for used values. And find diff between them.
var created = ["0000000040000", "0000000040001", "0000000040002"];
var used = ["0000000040001", "0000000040002"];
var unused = _.difference(created, used);

$.each function is not iterating

I am working with a relatively complex JSON structure and am unable to iterate through it via the $.each() function. I'm pretty sure it's something to do with the weird 2-dimensional array I am passing through in the value section of the normal array (hope that made sense). I am new to Ajax and JSON so just need some guidance on the best way to handle JSON when it is returned via an AJAX Call. Thanks!
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var i = 0;
for(var k in data){
window.alert(k);
} //this works
$.each(data, function(key, value){ //however this does not display anything
window.alert("should be outputted");
window.alert("key" + key + "value" + value[i]['email']);
i++;
});
});
JSON I am using:
{"bodge.com":[{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},{"email":"fwzqfjma#bodge.com","orders":"3","value":"13.71"},{"email":"rwsofs#bodge.com","orders":"7","value":"6.49"},{"email":"vfr#bodge.com","orders":"3","value":"24.36"},{"email":"wcs#bodge.com","orders":"3","value":"11.26"},{"email":"oqmsboag#bodge.com","orders":"3","value":"5.36"},{"email":"wdvm#bodge.com","orders":"6","value":"18.21"},{"email":"xubumenme#bodge.com","orders":"1","value":"10.24"},{"email":"pleqlwpha#bodge.com","orders":"2","value":"6.59"},{"email":"dqhdcnvw#bodge.com","orders":"10","value":"7.85"},{"email":"gyxymze#bodge.com","orders":"1","value":"15.51"},{"email":"otbbqcw#bodge.com","orders":"2","value":"7.92"},{"email":"afspqpq#bodge.com","orders":"3","value":"13.22"},{"email":"fwovyddw#bodge.com","orders":"4","value":"23.14"},{"email":"urczmgy#bodge.com","orders":"7","value":"15.17"},{"email":"hkgccna#bodge.com","orders":"4","value":"17.62"},{"email":"hlrnunyf#bodge.com","orders":"4","value":"22.03"},{"email":"gafoubu#bodge.com","orders":"10","value":"16.71"},{"email":"muwfjqs#bodge.com","orders":"4","value":"6.09"},{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},{"email":"jbq#bodge.com","orders":"8","value":"5.37"}],"bodge.com ":[{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}]}
Your JSON has (at least) two levels:
an object with keys ("bodge.com", "bodge.com "), and
each key holds an array of objects
{
"bodge.com": [
{"email":"mgbbuqc#bodge.com","orders":"2","value":"19.67"},
{"email":"vswmdkqtb#bodge.com","orders":"5","value":"21.89"},
...
{"email":"ddjeqvu#bodge.com","orders":"1","value":"23.88"},
{"email":"jbq#bodge.com","orders":"8","value":"5.37"}
],
"bodge.com ": [
{"email":"uytdlcgd#bodge.com ","orders":" 9 ","value":" 21.22"}
]
}
In order to iterate through the structure, you will need at least two levels of iteration:
$.each(data, function(domain, objects) {
console.log(domain); // will output "bodge.com" or "bodge.com "
$.each(objects, function(index, x) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
Note that you are using $.each for two different kinds of iteration: first over the keys and values of an object, then over the items in an array.
As an alternative, use Object.keys to get an array of an object's keys, and the forEach method:
Object.keys(data).forEach(function(domain) {
console.log(domain); // will output "bodge.com" or "bodge.com "
data[domain].forEach(function(x, index) {
console.log(x.email);
console.log(x.orders);
console.log(x.value);
console.log(index); // will output the 0-based position of x within the array
});
});
It looks like you should be bypassing data['bodge.com'] into the each function rather that simply data.
You could try this;
$.ajax({
type: 'POST',
url: 'model.php',
data: formData,
dataType: 'json',
encode : true
}).done(function(data){
var list = JSON.parse(data);
$.each(list, function(i){
alert(list[i].your_filed);
});
});

Return Random JSON object

I have JSON on AWS server that I access Using JQuery and inside that json file are a few hundred objects that I wish to loop through and pick out one at random. Then get the attributes for that object.
This is the JSON:
{
"1":{
"title":"Sailing for Kids",
"ISBN":"1909911267"
},
"2":{
"title":"True Spirit: The Aussie girl who took on the world",
"ISBN":"413513243"
},
..........
And this is how I am trying to get the json objects.
$(document).ready(function(){
$.ajax({
crossOrigin: true,
url : "https://link/to/file.json",
type : "GET",
success:function(data){
var randomItem = data[Math.random() * data.length | 0];
// take only the element with index 0
alert(randomItem[0]);
}
});
});
However, the alert is only displaying one character. like so:
How do I loop through all the returned JSON file the file, select one object and then get the attributes (title/ISBN) so that I can use them?
[
{
"1":{
"title":"Sailing for Kids",
"ISBN":"1909911267"}
},
{
"2":{
"title":"True Spirit: The Aussie girl who took on the world",
"ISBN":"413513243"}
}
]
you may need to construct JSON as above
First I'd do console.log(data) or even console.log(data[1]) to see what I actually get. It could be, depending on headers, that result is sent as a text and not an object, in that case you need to do data = JSON.parse(data)
And then, to get the actual length of the object, like it was suggested, you need to use Object.keys(data), or you may arrange your data in an array.
And if n is the length than Math.floor(Math.random() * n) would a random in that range.
EDIT:
Not being careful, Object.keys(data) is an array of keys. The length you need is thus Object.keys(data).length
EDIT 2:
var keys = Object.keys(data)
var n = keys.length;
var randomNumber = Math.floor(Math.random() * n);
var randomKey = keys[randomNumber];

Accessing data in a multidimensional JSON array with jQuery

I am trying to work out how to access data in an essentially multidimensional JSON array.
My jQuery AJAX request looks like this:
$("#login-form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/ajax/login',
data: 'email='+$("#email").val()+'&password='+$("#password").val(),
success: function(data){
// FIRE ALERT HERE
alert(data.firstname);
},
dataType: 'json'
});
});
This is what i am getting back. User account details, plus a list of products they have against their account.
{
"logged_in":true,
"firstname":"Joe",
"surname":"Bloggs",
"Full_name":"Joe Bloggs",
"email":"email#website.com",
"phone":"+123456789",
"website":"",
"age":"26-35",
"street":"1 Street Ave",
"city":"Townland",
"state":"NA",
"postcode":"1234",
"country":"Australia",
"products":2,
"0":{
"product_no":"1087",
"customer":"2",
"bought_from":"1",
"date_of_purchase":"2011-04-08",
"method":"instore",
"invoice":"0",
"current":"1"
},
"1":{
"product_no":"24",
"customer":"2",
"bought_from":"1",
"date_of_purchase":"2011-04-08",
"method":"instore",
"invoice":"0",
"current":"1"
}
}
As you can see, i am alerting the first name, which is fine. I can access everything in the first dimension by using data.key but i'm not sure how then i need to index the next dimension. Obviously I would like to display each of the products somehow.
Suggestions would be most welcome.
Inside your success function you can treat the JSON data as a JavaScript object. You can access the product array and objects inside it like this:
console.log(data.products + " product(s) in data"); // data.products is 2 (integer)
for(var i = 0; i < data.products; i++) { //
var product = data[i.toString()]; // 0.toString() is "0"
// data["0"] is what you want
// now product points to the property "0"
console.log(product.product_no); // so you can use product.xxx
// or product["xxx"]
} // likewise for "1", "2", "3" and so on
Replace console.log with alert if you do not know what console is.
Each of the product details can be accessed through data[iProductIndex.toString()] member. Data is stored inside data["0"] and data["1"], therefore to access them you need to convert integer value to string. Unfortunately you won't be able to use $.each loop because "0" and "1" are separate member objects. Use for loop with iProductIndex.
Data supplied does not allow for your answer, Salman A. See JSON Arrays for array definition, to have it work your way it must've been defined as
{"products" : [ {"product_no":"1087",
"customer":"2",
"bought_from":"1",
"date_of_purchase":"2011-04-08",
"method":"instore",
"invoice":"0",
"current":"1"} ] }
To OP:
alert(data["0"].product_no);
alert(data["1"]["date_of_purchase"]);
try this
<script type="text/javascript">
var json_string={
"logged_in":true,
"firstname":"Joe",
"surname":"Bloggs",
"Full_name":"Joe Bloggs",
"email":"email#website.com",
"phone":"+123456789",
"website":"",
"age":"26-35",
"street":"1 Street Ave",
"city":"Townland",
"state":"NA",
"postcode":"1234",
"country":"Australia",
"products":2,
"0":{
"product_no":"1087",
"customer":"2",
"bought_from":"1",
"date_of_purchase":"2011-04-08",
"method":"instore",
"invoice":"0",
"current":"1"
},
"1":{
"product_no":"24",
"customer":"2",
"bought_from":"1",
"date_of_purchase":"2011-04-08",
"method":"instore",
"invoice":"0",
"current":"1"
}
};
for (key in json_string) {
// Most modern browsers should have hasOwnProperty by now.
// This keeps us from getting farther up the chain.
if (json_string.hasOwnProperty(key)) {
document.write(key + "->" + json_string[key]);
document.write("<br>");
}
};
var pro_1= json_string[0]; // here u change 0 with 1 and get the data of "1"
for (key in pro_1) {
if (pro_1.hasOwnProperty(key)) {
document.write(key + "->" + pro_1[key]);
document.write("<br>");
}
};
</script>

Categories

Resources