forEach is not a function even with JSON.parse - javascript

I am having trouble with looping JSON data. I always get the error data.forEach is not a function even do i use JSON.parse. Anyone know how to fix this problem ?
function getApiGebruiker() {
CallWebAPI();
//nieuw deel
var url = "http://localhost:8081/persoons";
//do get request
var client = new HttpClient();
client.get("http://myIPadress/persoons", function (response) {
// do something with response
var data = JSON.parse(response);
console.log(data);
//data = JSON.parse(data);
let string = document.getElementById("pwd").value;
let loginn = document.getElementById("login").value;
data.forEach((persoons) => {
console.log(persoons.gebruikersnaam);
});
});

Your data seems to be an object ({}) and not an array ([]).
Try:
var data = JSON.parse(response);
var people = data._embedded.persoons
people.forEach((persoon) => {
console.log(persoon.gebruikersnaam);
});

Related

How do I get a buried variable from a JSON file?

This is probably a very novice question, but I am a very novice programmer, so here goes...
I am using GAS and Google Books to get the url for a book cover using this code:
function myFunction() {
var url = "https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&country=US"
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(response);
}
From my limited knowledge, I tried using this to get the proper URL:
Logger.log(data.items.imageLinks.smallThumbnail);
but it just returns an error. Is there something missing or a different way to get the variable I need?
The issue is that data.items is an array of 10 elements, therefore you have to index that.
If you want to access the first element:
function myFunction() {
var url = "https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&country=US"
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
console.log(data.items.length)
Logger.log(data.items[0].volumeInfo.imageLinks.smallThumbnail);
}
If you want to access all elements and store it in an array:
function myFunction() {
var url = "https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&country=US"
var response = UrlFetchApp.fetch(url);
var json = response.getContentText();
var data = JSON.parse(json);
var items = data.items;
var smallThumbnails = items.map(x=>x.volumeInfo.imageLinks.smallThumbnail);
Logger.log(smallThumbnails);
}
Output:
[http://books.google.com/books/content?id=gK98gXR8onwC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=LRlCAAAAYAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=Fgn65IL3q4wC&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=3vFDvgAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=gK98gXR8onwC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=F1wgqlNi8AMC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=64tuPwAACAAJ&printsec=frontcover&img=1&zoom=5&source=gbs_api, http://books.google.com/books/content?id=wAUiAAAAMAAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=7hLQ_F0obXAC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api, http://books.google.com/books/content?id=tVxnDwAAQBAJ&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api]

JS: Textfile to JSON

im a complete beginner to JS and need some help.
I have a Textfile looking like this:
JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON
2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held
2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held
2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None
So JOBID, NAME and so on are the Names for the values below.
Now I want to parse it into a JSON object.
I tried to do it like this:
var jdata = new Array();
jdata = data.toString().split('\n');
jsonstring = JSON.stringify(jdata);
fs.writeFile('out/data.json', jsObj, (err) => {
if (err) throw err;
});
But the result is no JSON object right?
I somehow need to attach connect the parameters to each other so it looks like:
{
"JOBID": 2527,
"NAME": '_DP-2-Q-095-84-1-50.job',
...
}
Somebody can tell me how to convert this correctly or isn't it even possible this way?
Thank you already
You've started correctly but you cannot simply use JSON.stringify(jdata); to convert to JSON. An example in pure JS is like so:
//Load in Input
var input = `JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON
2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held
2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held
2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None`;
//Split into Lines
var data = input.split("\n");
//Get all the header values
var header = input.split("\n")[0].split(",");
//Init Output Array
var output = [];
//For every row except the first (1...n)
for(var i=1;i<data.length;i++){
//Get all the values
var values = data[i].split(",");
var obj = {};
//For every value in the header
for(var j=0;j<header.length;j++){
//obj[JOBID] = 2527
obj[header[j]] = values[j];
}
//Push to output
output.push(obj);
}
Output now will equal your array of objects. You can then save it as you did before.
// [{"JobID": 2527, "...},{..}...]
jsonstring = JSON.stringify(output);
fs.writeFile('out/data.json', jsObj, (err) => {
if (err) throw err;
});
You are correct that you need to transform your data before it becomes a proper JSON object.
This is a way to do it (with a bit more modern Javascript):
const data = `JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON
2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held
2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held
2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None
`;
let lines = data.split('\n');
const headers = lines.shift().split(',');
// convert the individual lines to JSON objects
const jsonData = lines.map(line => {
const parts = line.split(',');
// Invalid lines - these are filtered out later
if (parts.length !== headers.length) {
return false;
}
// look up the name of the part from the header and use that as the property name
return parts.reduce((acc, part, index) => ({
...acc,
[headers[index]]: part,
}), {});
}).filter(Boolean); // remove the invalid objects
console.log(jsonData);
Here is a simple approach and you can modify it as for your need
var data = 'JOBID,NAME,USER,NODELIST,CPUS,STATE,REASON\n'
+'2527,_DP-2-Q-095-84-1-50.job,loe_mk,,4,PENDING,launch failed requeued held\n'+
'2528,_Q-095-76-2-05.job,fr_tho,,4,PENDING,launch failed requeued held\n'+
'2515,_DC-3-V-095-76-0-10.job,pi_tim,node01,4,RUNNING,None';
var spdata = data.split('\n');
//assuming that the first row is always having columns names
var names = spdata[0].split(',');
var mainDataAr=[];
//reading data from the 2nd row
for(var i=1;i<spdata.length;i++)
{
//taking the data from the row at position i
var rdata = spdata[i].split(',');
var obj={};
for(var j=0;j<names.length;j++)
{
obj[names[j]]=rdata[j]
}
mainDataAr.push(obj);
}
console.log(mainDataAr);

Can't get the value of json object

I have this json object, and i want to get the value of the error but it always returning me an undefined result.
Here is the json object
{"isValid":false,"errors":["Username is required.","Password is required."]}
my code is:
success: function (response) {
var JSONstring = JSON.stringify(response);
var JSONobject = JSON.parse(JSONstring);
alert(JSONstring);
alert(JSONobject);
console.log(JSONobject);
var _result = JSONobject.errors;
i have also tried:
var _result = JSONobject[0]['errors'];
var _result = JSONobject['errors'][0];
but still i can't access the value.
If you already have access to the JSON object you can work with it without manipulation. If your question was also looking to get it in that form, see this StackOverflow answer for how to format your request.
success: function (response) {
// Assuming response = {"isValid":false,"errors":["Username is required.","Password is required."]}
// Directly access the property errors
var errors = response.errors;
console.log(errors); // ["Username is required.","Password is required."]
JSFiddle

Getting HTTP Response using restler in Node.js

I don't understand why this code doesn't work for me
var rest = require('restler');
var getResp = function(url){
var resp ="";
rest.get(url).on('complete',function(response){
resp = response.toString();
});
return resp;
};
I am not getting the response for getResp('google.com')
Am I missing something with restler?
Being that you're returning resp it looks like you've forgotten that the request is asynchronous. Instead try out this:
var rest = require('restler');
var getResp = function(url){
rest.get(url).on('complete', function(response){
console.log(response);
});
};
getResp('http://google.com/');
// output:
// <!doctype html><html itemscope="itemscope" ....
Because of its asynchronous nature it's preferred that you pass the value to a receiving callback. Take this small example:
var rest = require('restler');
// process an array of URLs
['http://google.com/',
'http://facebook.com/'].forEach(function(item) {
getResp(item);
});
function getResp(url){
rest.get(url).on('complete', function(response){
processResponse(response);
});
};
// data will be a Buffer
function processResponse(data) {
// converting Buffers to strings is expensive, so I prefer
// to do it explicitely when required
var str = data.toString();
}
Once the data comes in you'll be able to pass it around like any other variable.
return resp; is running before the on('complete' callback gets called because it is asynchronous. This is resulting is the resp variable never getting assigned a value.
Try this:
var rest = require('restler');
var getResp = function(url){
var result = rest.get(url).on('complete', function(response){
response;
});
return result;
};
getResp('http://google.com/');
You could also use a callback like in this SO answer.

Get json value from response

{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
If I alert the response data I see the above, how do I access the id value?
My controller returns like this:
return Json(
new {
id = indicationBase.ID
}
);
In my ajax success I have this:
success: function(data) {
var id = data.id.toString();
}
It says data.id is undefined.
If response is in json and not a string then
alert(response.id);
or
alert(response['id']);
otherwise
var response = JSON.parse('{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}');
response.id ; //# => 2231f87c-a62c-4c2c-8f5d-b76d11942301
Normally you could access it by its property name:
var foo = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"};
alert(foo.id);
or perhaps you've got a JSON string that needs to be turned into an object:
var foo = jQuery.parseJSON(data);
alert(foo.id);
http://api.jquery.com/jQuery.parseJSON/
Use safely-turning-a-json-string-into-an-object
var jsonString = '{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';
var jsonObject = (new Function("return " + jsonString))();
alert(jsonObject.id);
var results = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}
console.log(results.id)
=>2231f87c-a62c-4c2c-8f5d-b76d11942301
results is now an object.
If the response is in json then it would be like:
alert(response.id);
Otherwise
var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

Categories

Resources