Object retrieval from JSON using Jquery / JS - javascript

I have a JSON file at /path/to/json containing:
{"a": {"s": [{"l": "PPP"}]}}
I'm using this JQuery expression:
$.ajax({
url: '/path/to/json',
dataType: 'json',
async: false,
success: function(data) {
$.each(data.a.s, function(index,element) {
lines=element.l;
})
}
});
How do I return the value at a.s.l without using $.each()?
I have another JSON file containing:
{"a": {"s": [
{
"l": "PPP",
"qqq": "aaa"
},
{
"l": "FFF",
"qqq": "bbb"
}
]}}
This is a file. How do I assign the contents of the file to a variable then search within this json for the object who's 'l' attribute is 'PPP' then retrieve that object's 'qqq' value?

You can use the array index, if you know the index of item to be fetched
To get the first item in the s array
data.a.s[0].l
To get the second item in the s array
data.a.s[1].l
Or use a for loop
for(var i= 0; i<data.a.s.length; i++){
lines = data.a.s[i].l
}

Related

Cannot use IN operator in Javascript when looping through JSON

I have a Json response, it looks like this:
[{
"item": "1",
"addr": "someaddr"
},
{
"item": "2",
"addr": "someotheraddr"
}
]
How can i loop through this record and print, let's say, the addr field of each one?
I tried the following:
$.ajax({
url: "someurl",
type: 'get'
success: function (data) {
$.each(data, function(key, val) {
console.log(key, val)
});
alert("Success");
}
});
But it throws the following error: TypeError: Cannot use 'in' operator to search for 'length'
I'm sure it's because i'm not properly looping throught the Json Data. Can someone point me out where i'm breaking the loop?
Edit: the Json response is retrieved from an API endpoint using Jquery.
You need to use dataType: 'json' to tell jQuery to parse the response as JSON (if the server doesn't send Content-type: application/json).
$.ajax({
url: "someurl",
type: 'get',
dataType: 'json',
success: function (data) {
$.each(data, function(key, val) {
console.log(key, val.addr)
});
alert("Success");
}
});
The problem may be that you're not passing back a JSON object, you're passing back individual lines of JSON. So if you have control over your JSON response, you should make the json look like this:
[
{"item": 1, "addr": "someaddr"},
{"item": 2, "addr": "someotheraddr"}
]
(note that it is wrapped in an array, has commas between each line, and has double quotes around the strings).
Then you can use your each function. I have included a snippet below that you can try it out with.
var data = [
{"item": 1, "addr": "someaddr"},
{"item": 2, "addr": "someotheraddr"}
];
$.each(data, function(key, val) {
console.log(val.addr)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

Can't loop through JSON data

I'm a real noob when it comes to JSON. Any help on the following would be fantastic.
console.log(obj.id); in the code below returns nothing in the console - I need to understand why? I expect it two log two things in the console based on the JSON data.
JS:
var matchTeamAStatsJSON
$.ajax({
type: 'GET',
url: 'http://www.website.com/apipathblahblahblah',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
matchTeamAStatsJSON = data;
console.log(matchTeamAStatsJSON);
for(var i = 0; i < matchTeamAStatsJSON.length; i++) {
var obj = matchTeamAStatsJSON[i];
console.log(obj.id);
}
}
})
JSON:
{
"records": [
{
"id": "recGWUWqwjUNLpekA",
"fields": {
"playerSprints": 12,
"playerDistanceCovered_km": 6.23
},
"createdTime": "2018-03-22T18:16:56.000Z"
},
{
"id": "recx5pMFpxnRwR4La",
"fields": {
"playerSprints": 12,
"playerDistanceCovered_km": 6.23
},
"createdTime": "2018-03-19T11:35:11.000Z"
}
]
}
You could use Array.prototype.forEach() and do:
const data = {"records": [{"id": "recGWUWqwjUNLpekA","fields": {"playerSprints": 12,"playerDistanceCovered_km": 6.23},"createdTime": "2018-03-22T18:16:56.000Z"},{"id": "recx5pMFpxnRwR4La","fields": {"playerSprints": 12,"playerDistanceCovered_km": 6.23},"createdTime": "2018-03-19T11:35:11.000Z"}]};
data.records.forEach(obj => console.log(obj.id));
If the JSON example you posted below is the response from the GET request, data is equal to "records" which doesn't have an and "id" property. However, each instance of the array it contains does.
You need to get inside that array first and then get the "id" property of each element: console.log(obj.records[i].id) should get you want.
Hope this helps!

Send non-editable Array with JSON & Ajax

Is it possible to send non-editable arrays?
What i'm trying to send is:
var items = [];
//console.log(JSON.stringify(items));
allitems = JSON.stringify(items);
[{
"assetid": "7814010469",
"classid": "1797256701",
"instanceid": "0",
"name_color": "D2D2D2",
"icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFYznarJJjkQ6ovjw4SPlfP3auqEl2oBuJB1j--WoY322QziqkdpZGr3IteLMlhpw4RJCv8",
"market_hash_name": "Gamma Case"
}]
$.ajax({
type: "POST",
async: true,
url: "jackpot/deposit",
data: {
myData: allitems
},
success: function(body) {
toastr["info"]("Success! Our bots are generating your trade. Please wait...", "Inventory");
},
});
But I want to make it not editable via the console.
And send it.
You should be able to use Object.freeze() to prevent the array from being changed. For example:
var arr = [1, 2, 3];
Object.freeze(arr);
arr.push(4); // error

Filter Key value of json on ajax success

Is there a way to filter my key value.I want to filter key where my key is REF, and my value is text1. Get the result where a key is REF and my value is text1 . I want to access each key value separate when the result is returned. Like alert(SNO, value); where SNO is my key and the Value that is returned from my filter result
<script type="text/javascript">
function ClientNodeClicking(sender, eventArgs) {
var node = eventArgs.get_node();
var text1 = node.get_text();
var text2 = node.get_value();
$.ajax({
type: "POST",
url: "A2_JVV.aspx/ds2json",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#Result").text(msg.d);
$.each(msg, function (key, value) {
console.log(key, value);
});
}
});
alert(text1);
}
</script>
this is what i get in my chrome console
d [
{
"REF": "JVV-001441",
"SNO": 1.0,
"mdate": "2015-08-15T00:00:00",
"date": "15/08/2015",
"INITIAL": "G",
"ACNO": "02010219",
"TITLE": "S S ENT. ON LINE A/C",
"JOB_ID": "00000",
"JOB": "0-N/A",
"cRR": 0.00,
"dRR": 500000.00,
"U_INSERT": "KHURRAM",
"I_DATE": "2015-08-15T14:09:19.997",
"U_EDIT": null,
"E_DATE": null,
"DISC": "RECEIVED ON LINE SLIP NO#5794 MEEZAN S S A/C (AMJAD ANJUM)"
},
{
"REF": "JVV-001441",
"SNO": 2.0,
"mdate": "2015-08-15T00:00:00",
"date": "15/08/2015",
"INITIAL": "C",
"ACNO": "020101039",
"TITLE": "AMJAD ANJUM",
"JOB_ID": "00000",
"JOB": "0-N/A",
"cRR": 500000.00,
"dRR": 0.00,
"U_INSERT": "KHURRAM",
"I_DATE": "2015-08-15T14:09:20.01",
"U_EDIT": null,
"E_DATE": null,
"DISC": "RECEIVED ON LINE SLIP NO#5794 MEEZAN S S A/C"
}
]
If you want to filter any array you can use the core .filter() method of every array.
It builds a new array by iterating over every element. It will call the provided callback passing it the element in the array and if the callback returns true that element will be put into the new array, otherwise it will be ignored.
So something like this would filter out all elements in your array where the property REF is not equal to text1;
var x = d.filter(function (item) {
return item.REF === 'text1';
});
You last requirement sounds like you want to iterate over each objects properties rather than access them directly. This can be done with a for in loop however the order the properties are iterated in cannot be guaranteed.
Something like this:
x.forEach(function (item){
//forEach iterates over every object in array
for(var i in item) {
//for in iterates over every property in item
console.log(i, item[i]);
}
});
Also because most core array methods, filter, forEach, map return the new array they can be chained.
EDIT: I lie, forEach does not return it self so cannot be chained afterwards. the others mentioned do however.
so:
var x = [].filter().map();
instead of
var x = [].filter();
x = x.map();
See fiddle: http://jsfiddle.net/cgzbvpoe/1/

Accessing values inside single array of JSON objects

I have wasted two days on this and I can't take it anymore. I am getting well formed JSON data from my $.ajax call. Sample below...
"results":[
"{"a":"data","b":"data","c":"data","d":"data"}",
"{"a":"data","b":"data","c":"data","d":"data"}",
"{"a":"data","b":"data","c":"data","d":"data"}",
"{"a":"data","b":"data","c":"data","d":"data"}"
]
I have attempted to access the values in this single array of JSON objects and just can't figure it out. Here's my code below...
success:function (data) {
/*
$.each(data.results, function(i, val) {
console.log(i, val);
});
*/
$('a.previewUrl').each(function (i) {
var res = jQuery.parseJSON(data.results[0]);
var previewUrl = $(this);
if(previewUrl.attr("href") == '') {
previewUrl.attr("href", res[i].d);
}
});
} // end success
The console.log iteration over each JSON object in the array prints out fine but I think I have tried a dozen different ways to grab these values in the $.each() loop. What I am missing?
Your Json isn't valid. Try putting it through jsonlint and see what happens.
I think this could be what you were aiming for:
{
"results": [
{
"a": "data",
"b": "data",
"c": "data"
},
{
"a": "data",
"b": "data",
"c": "data"
},
{
"a": "data",
"b": "data",
"c": "data"
},
{
"a": "data",
"b": "data",
"c": "data"
}
]}
and if you're using jQuery's $.getJSON function, you don't need to parse your data or if you're using the $.ajax function, set the datatype to json so it wil parse the data for you.

Categories