Can't loop through JSON data - javascript

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!

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>

How can I give my JSON dictionary a main key, without implementing it into my loop?

I am translating some code from python into Javascript (I am inexperienced in JS), as part of it I need to write a JSON, currently when writing in JS it looks like this(just a brief sample):
[
{
"Num": "000000",
"Status": 1,
},
{
"Num": "00001",
"Status": 0,
},
]
However I need it to look like this:
{
"mydata": [
{
"Num": "00000",
"Status": 1,
},
{
"Num": "00001",
"Status": 0,
},
]
}
How can I adapt my code to generate this single main key for the whole JSON, here is what I have so far:
var jsondata = []
for (result in results) {
jsondata.push({
'Num' : idnum,
'Status': results[result].StatusID,
})
}
let data = JSON.stringify(jsondata, null, 2)
fs.writeFileSync('testingjson.json', data)
This code here sits in a for loop, so I cannot just write the key in the push, it would generate the mydata key for every iteration of the loop.
I need to know how I can pre-define the mydata, has anyone got a good method to do this?
Just define mydata as an array, and then at the end, create an object where mydata is one of the keys:
const mydata = []
for (const result in results) {
mydata.push({
'Num' : idnum,
'Status': results[result].StatusID,
});
}
const json = JSON.stringify({ mydata }, null, 2);
If you want to use a different key name, then change it when stringifying, eg:
const json = JSON.stringify({ someKeyName: mydata }, null, 2);
If results is an object, then you can make the code more concise with Object.values and map:
const Num = idnum;
const mydata = Object.values(results)
.map((item => ({ Num, Status: item.StatusID }));
const json = JSON.stringify({ mydata }, null, 2);
fs.writeFileSync('testingjson.json', data)

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

Create json tree structure with children

I have a json tree structure that is appended to by pressing invoke on this fiddle : http://jsfiddle.net/adrianjsfiddlenetuser/C6Ssa/4/
Press invoke multiple tiles on the fiddle & copy/paste the produced jSon intohttp://jsonlint.com/, the produced json is not valid
I need to produce this :
{
"nodes": [
{
"url": "asdfas",
"date": ""
},
{
"url": "asdfas",
"date": ""
},
{
"url": "asdfasfdasas",
"date": ""
}
]
}
Can this be amended so that multiple children can be added to the tree structure, I think I need to amend the var data somehow ?
Try:
var data = {nodes: []};
$("#add").on('click', function () {
data.nodes.push({
url: "some url",
date: new Date
});
$("#myDiv").text(JSON.stringify(data));
});
if not, I didn't understand your question ;)
http://jsfiddle.net/gY5yQ/
See if this helps http://jsfiddle.net/C6Ssa/12/
var data = [];
$("#add").click(add);
function add() {
data.push({
param1: "stuff",
param2:1,
param3:1
});
var sample = {};
sample.node = data
$("#myDiv").text(JSON.stringify(sample));
}

Categories