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
Related
I am having trouble to display the top tracks of a searched artist using the LastFM api to get data. The api returns an object toptracks. I would like to grab details about each of the top tracks from that api data.
I am not sure if I am on the right track. Can someone take a look and let me know if I am doing something wrong?
Sample data from api:
{
"toptracks": {
"track": [{
"name": "Best I Ever Had",
"playcount": "3723918",
"listeners": "1086968",
"mbid": "00bde944-7562-446f-ad0f-3d4bdc86b69f",
"url": "https://www.last.fm/music/Drake/_/Best+I+Ever+Had",
"streamable": "0",
"artist": {
"name": "Drake",
"mbid": "b49b81cc-d5b7-4bdd-aadb-385df8de69a6",
},
"#attr": {
"rank": "1"
}
},
{
"name": "Forever",
"playcount": "1713492",
"listeners": "668998",
"url": "https://www.last.fm/music/Drake/_/Forever",
"streamable": "0",
"artist": {
"name": "Drake",
"mbid": "b49b81cc-d5b7-4bdd-aadb-385df8de69a6",
},
"#attr": {
"rank": "2"
}
}
}
function renderTracks(trackArray) {
function createHTML(track){
return `<h1>${track.name}</h1>
<h2>${track.artist[0]}</h2>
<h3>${toptracks[1].rank}</h3>
<h3>${track.playcount}</h3>`;
};
trackHTML = trackArray.map(createHTML);
return trackHTML.join("");
};
var searchString = $(".search-bar").val().toLowerCase();
var urlEncodedSearchString = encodeURIComponent(searchString);
const url = "lastFMwebsite"
axios.get(url + urlEncodedSearchString).then(function(response) {
// createHTML.push(response.data.track);
// $(".tracks-container").innerHTML = renderTracks(response.data.track);
// comented out old code above
createHTML.push(response.toptracks.track);
$(".tracks-container").innerHTML = renderTracks(response.toptracks.track);
})
I've notice that you have not parsed the response:
axios.get(url + urlEncodedSearchString).then(function(response) {
var parsed = JSON.parse(response);
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks.track)
});
Another correction that I can suggest is to change the track.artist[0] to track.artist["name"] once this property returns an object instead of an array.
And about this: <h3>${toptracks[1].rank}</h3>. You will be not able to access that property because at your function you are providing just the trackproperty.
In this case you have two options: provide the whole response array or add a new parameter providing this.
function renderTracks(trackArray) {/**...*/};
//...
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks)
Or
function renderTracks(trackArray, toptracks) {/**...*/};
//...
$(".tracks-container").innerHTML = renderTracks(parsed.toptracks.track, parsed.toptracks)
I hope this can help you :)
Your input JSON is not valid. You'll need to format it correctly. Once the data is correct:
createHTML.push(response.toptracks.track[0])
or
let i = 0;
for(; i < response.toptracks.track.length; i++){
createHTML.push(response.toptracks.track[i]);
}
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!
{
"3": {
"id": "3",
"ocena_ocena": "2",
"ocena_profesor": "\u041c\u0430\u0440\u043a\u043e \u041c\u0430\u0440\u043a\u043e\u0432\u0438\u045b",
"ocena_napomena": "",
"ocena_datum": "31.12.2015."
},
"1": {
"id": "1",
"ocena_ocena": "5",
"ocena_profesor": "\u041c\u0430\u0440\u043a\u043e \u041c\u0430\u0440\u043a\u043e\u0432\u0438\u045b",
"ocena_napomena": "",
"ocena_datum": "22.12.2015."
}
}
I am using ajax to get this JSON. I tried parsing it like this:
request.done(function(response) {
alert(response.ocena_ocena);
});
Could someone please help me with this?
I also need to know how can I do a foreach statement with json?
Since your JSON represents a JavaScript object, you should include the attribute name (if we consider JavaScript object to be a map, then, we need to use the key).
Try
response["1"].ocena_ocena
or
response["3"].ocena_ocena
Since you are returning a JSON object from server instead of an array, to iterate over its properties, you could do
for (var i in response) {
console.log(response[i].ocena_ocena);
}
or
Object.keys(response).forEach(function f(e) {console.log(response[e].ocena_ocena)})
If you could modify your server side code to return JSON that looks like this,
[
{
"id": "3",
"ocena_ocena": "2",
...
},
{
"id": "1",
"ocena_ocena": "5",
...
}
]
then you could iterate over it more easily
response.forEach(function f(e) {console.log(e.ocena_ocena)})
I'm trying to parse data to a collection view from a json file that has number key for each group of data within it. The JSON looks like this:
{
"0": {
"artifact_id": "36",
"timestamp": "2013-08-20 11:59:00",
"modified": "2013-08-20 11:59:00",
"text": "Why did the last one duplicate? I don't think I clicked it twice...",
"author_desc": "",
"object_type": "artifact",
"comments": []
},
"1": {
"artifact_id": "35",
"timestamp": "2013-08-20 11:57:51",
"modified": "2013-08-20 11:57:51",
"text": "This is a new artifact for a new day.",
"author_desc": "",
"object_type": "artifact",
"comments": []
},
"2": {
"artifact_id": "34",
"timestamp": "2013-08-20 11:57:50",
"modified": "2013-08-20 11:57:50",
"text": "This is a new artifact for a new day.",
"author_desc": "",
"object_type": "artifact",
"comments": []
}
}
How do I write a model parse to take each one of the entries (0, 1, 2... etc) as each model from within the data?
This is my collection, with the suggested addition from Casey below, however it doesn't seem to be running the parse method:
var FriendCollection = Backbone.Collection.extend({
model: FriendModel,
parse: function(data) {
console.log('running parse');
return _.map(data, _.identity);
}
});
var friendCollection = new FriendCollection();
friendCollection.reset(friendjson);
Collection#reset does not call parse and there's no way to make it call parse. You have a few options:
Convert friendjson to an array by hand and give reset that array.
Don't reset at all, just hand friendjson to the collection's constructor and include the {parse: true} option.
Replace your collection's reset with your own version that does call parse if you include a {parse: true} option.
1 should be pretty obvious.
2 would look like this:
var friendCollection = new FriendCollection(friendjson, { parse: true });
Demo: http://jsfiddle.net/ambiguous/dbM82/
3 would look something like this:
var FriendCollection = Backbone.Collection.extend({
//...
reset: function(models, options) {
if(options && options.parse) {
delete options.parse;
models = this.parse(models);
}
return Backbone.Collection.prototype.reset.call(this, models, options);
}
});
var friendCollection = new FriendCollection();
friendCollection.reset(friendjson, { parse: true });
Demo: http://jsfiddle.net/ambiguous/Rs8es/
Use the Collection#parse method.
var MyCollection = Backbone.Collection.extend({
parse: function (data) {
return _.map(data, _.identity);
}
});
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));
}