Cannot use IN operator in Javascript when looping through JSON - javascript

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>

Related

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!

How to get specific data from nested JSON

I'm trying to get the nested station names using jQuery and display the names in a 'div'. I'm able to display the contents of 'jObject' however, I'm unable to get to the specific station name.
This is what i have tried so far.
$.ajax({
url: "https://transportapi.com/v3/uk/tube/stations/near.json?app_id=appid&app_key=key&lat=" + lat + "&lon=" + lng + "&page=1&rpp=5",
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
//console.log(data);
var jObject = data.stations;
// $('#stationName').append(JSON.stringify(jObject));
$.each(jObject.name, function(index, element) {
$('#stationName').append(JSON.stringify(jObject.name));
});
}
});
JSON structure
{
"minlon": -0.23437,
"minlat": 51.434842,
"maxlon": -0.03437,
"maxlat": 51.634842,
"searchlon": -0.13437,
"searchlat": 51.534842,
"page": 1,
"rpp": 1,
"total": 147,
"request_time": "2018-03-09T17:15:22+00:00",
"stations": [
{
"station_code": "MCR",
"atcocode": "9400ZZLUMTC",
"name": "Mornington Crescent",
"mode": "tube",
"longitude": -0.13878,
"latitude": 51.53468,
"lines": [
"northern"
],
"distance": 492
}
]
}
You should use $each on jObject and not on jObject.name. And you need to specify index while getting name as stations is an array of objects or just use element.name
var data={
"minlon": -0.23437,
"minlat": 51.434842,
"maxlon": -0.03437,
"maxlat": 51.634842,
"searchlon": -0.13437,
"searchlat": 51.534842,
"page": 1,
"rpp": 1,
"total": 147,
"request_time": "2018-03-09T17:15:22+00:00",
"stations": [
{
"station_code": "MCR",
"atcocode": "9400ZZLUMTC",
"name": "Mornington Crescent",
"mode": "tube",
"longitude": -0.13878,
"latitude": 51.53468,
"lines": [
"northern"
],
"distance": 492
}
]
};
var jObject = data.stations;
$.each(jObject, function(index, element) {
console.log(jObject[index].name);
console.log(element.name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
There are a few things wrong in your code:
$.each() will iterate on an array, since you already define data.stations as jObject, you need to iterate in that array.
$.each function takes to parameters index and element, the first one is the position of the element in the array, and the second has the element itself.
So the code will be:
var jObject = data.stations;
$.each(jObject, function(index, element) {
$('#stationName').append(element.name);
});
Check the JSFIDDLE

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

unable to access value of JSON array in javascript

In my javascript I am trying to read values from a JSON file from a server. The file contains a array of objects but I cannot access the values in these objects. When I try this my log says the value is undefined. However, when I try to stringify a Object in the array it works perfectly fine. What am I doing wrong?
The JSON file:
{
"NETWORKS": [
{
"NETWORK": {
"STARTDATE": "00:13:33:15:10:2015",
"SSID": "Ziggo323_AC",
"WPA": "YES",
"WEP": "NO",
"WPS": "YES",
"OPEN": "NO",
"WPATEST": {
"DURATION": "3000",
"DATE": "00:11:26:24:09:2015",
"ATTEMPTS": "594",
"STATUS": "FAILED"
},
"WPSTEST": {
"DURATION": "2932",
"DATE": "03:11:28:24:09:2015",
"ATTEMPTS": "9",
"STATUS": "PASSED"
}
}
},
{
"NETWORK1": {
"STARTDATE": "00:15:26:15:10:2015",
"SSID": "FreeWiFi",
"WPA": "NO",
"WEP": "NO",
"WPS": "NO",
"OPEN": "YES"
}
}
]
}
The javascript function
function LoadTestResults() {
$.ajax({
type: 'POST',
url: 'GetJSON.php',
data: "TestResults.json",
dataType: "json",
success: function (data) {
var wpsDuration = data.NETWORKS[0];
console.log(JSON.stringify(wpsDuration)); // output ={"NETWORK":{"STARTDATE":"00:13:33:15:10:2015" etc.
console.log(wpsDuration.WPA); // output = undefined
}
});
}
Just try with:
wpsDuration.NETWORK.WPA
or with a loop:
for (var k in data.NETWORKS) {
var network = data.NETWORKS[k];
var networkKey = Object.keys(network).pop();
console.log(networkKey, network[networkKey].WPA);
}
Put a debugger; before this line var wpsDuration = data.NETWORKS[0]; and inspect the data.
Keep your console open while debugging. Once the success will reach
debugger will hit.
then move to console window and try different combinations. This will
help you to understand your object.
I tried and it worked for me
Put a debugger; before this line var wpsDuration = data.NETWORKS[0]; and inspect the data

Object retrieval from JSON using Jquery / JS

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
}

Categories