Convert a string to multi-dimensional array in javascript - javascript

This is returned by the REST API: [[5671, 204], [5673, 192], [5674, 120], [5683, 120], [5684, 192], [5685, 204]]
when i am doing typeof i am getting string for above in javascript . i want to convert it to a multi dimensional array.
<script type="text/javascript">
const Http = new XMLHttpRequest();
const url='/hello/get_pw_status';
Http.open("GET", url);
Http.send();
var resp;
Http.onreadystatechange = (e) => {
console.log(Http.responseText);
document.getElementById("demo").innerHTML =Http.responseText;
console.log(typeof Http.responseText);
var pw_data = [];
pw_data=Http.data;
console.log(pw_data);
}

Use JSON.parse to convert the array in the response string.
<script type="text/javascript">
const Http = new XMLHttpRequest();
const url='/hello/get_pw_status';
Http.open("GET", url);
Http.send();
var resp;
Http.onreadystatechange = (e) => {
var multiDimentionalArray;
if(typeof Http.responseText == "string") {
multiDimentionalArray = JSON.parse(Http.responseText);
}
conosle.log(multiDimentionalArray);
}

Related

How to get values from JSON XMLHttpRequest?

I am new to web development, and I am using a XMLHttpRequest() in JavaScript to get data from an api. I am trying to create variables from the data but am getting an error when I try to do the following. Does anyone know what is wrong with the line var data1 = data["data1"];?
<script>
const Http = new XMLHttpRequest();
const url = "www.mytestapi.com/response.json";
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var json = JSON.parse(Http.responseText)
var data = json.Data
var data1 = data["data1"]; //issue caused here
}
<script>
you don't need to parse response data, data is parsed already , try this
const xhr = new XMLHttpRequest();
const url = "www.mytestapi.com/response.json";
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
console.log("load - "+ JSON.stringify(xhr.response));
var data = xhr.response;
var data1 = data["data1"]
}
xhr.onerror = () => {
console.log("error status - " + xhr.status);
}
xhr.send()

Protractor - How do I pass a string value from a previous function to an async script?

The issue I'm having is that I have a dynamic API call whose url changes everytime. So In order to get the proper URL I have to get the text on the page and parse it so it only the first part of the text, then concatenate that to the first part of the URL. When I try to pass the string to the async script it keeps coming up as undefined. How can I get the string into the async script?
Specifically get the string to this line of code:
xhr.open("GET", APIcall, true);
var ID = element(by.css(".sometext")).getText().then(function(getFirstPartOfText) {
//console.log(ID);
var thing = getFirstPartOfText
var thing2 = getFirstPartOfText.toString().split(" ");
var thing3 = thing2[0];
var API = "https://someAPIcall/read/";
APIcall = API + thing3;
return APIcall;
}).then(function(APIcall){
console.log(APIcall);
browser.executeAsyncScript(function(ApiCall) {
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open("GET", APIcall, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send('');
}).then(function(str) {
console.log(str);
//var whatINeed = JSON.parse(str);
var ID = element(by.css(".sometext")).getText().then(function(getFirstPartOfText) {
// this is synchronous, so there's no need to chain it using .then()
var thing = getFirstPartOfText
var thing2 = getFirstPartOfText.toString().split(" ");
var thing3 = thing2[0];
var API = "https://someAPIcall/read/";
APIcall = API + thing3;
return APIcall;
});
call_something(ID); // ID should be set at this point.
function call_something (APIcall) {
console.log(APIcall);
browser.executeAsyncScript(function(ApiCall) {
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open("GET", APIcall, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send('');
}).then(function(str) {
console.log(str);
}
}
There are multiple things going on here, first of all the callback in call_something is not required, you are still within webdriver's promise manager. So all you need to do is return the data for the next call chain. Also quote in xhr.send(''); inside the method are not required. All you need to do is call send() and JSON parse the response and return, the next then block should have the JSON result. If you are getting pure HTML, then make sure the URL is correct.
function call_something (APIcall) {
console.log(APIcall);
browser.executeAsyncScript(function(ApiCall) {
var xhr = new XMLHttpRequest();
xhr.open("GET", APIcall, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
return JSON.parse(xhr.responseText);
}
};
xhr.send();
}).then(function(str) {
console.log(str);
}
}
I was missing an extra parameter mentioned here
The first argument is a function which will be called
The second+ arguments will be passed as arguments to the function in the first argument.
var ID = element(by.css(".sometext")).getText().then(function(getFirstPartOfText) {
//console.log(ID);
var thing = getFirstPartOfText
var thing2 = getFirstPartOfText.toString().split(" ");
var thing3 = thing2[0];
var API = "https://someAPIcall/read/";
APIcall = API + thing3;
return APIcall;
}).then(function(APIcall){
console.log(APIcall);
browser.executeAsyncScript(function(ApiCall) {
var callback = arguments[arguments.length - 1];
var xhr = new XMLHttpRequest();
xhr.open("GET", APIcall, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
callback(xhr.responseText);
}
};
xhr.send('');
}, APIcall).then(function(str) {
console.log(str);
//var whatINeed = JSON.parse(str);

How should I loop through this JSON data?

Here is my code I want to print out "song" property from data. Link to JSON is -> http://starlord.hackerearth.com/sureify/cokestudio
<script type="text/javascript">
var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var myjsondata = request.response;
showdata(myjsondata);
}
function showdata(data){
var song_name = data;
for (i = 0; i < 3; i++) {
document.write(song_name);
document.write("<br>");
}
}
</script>
When I run it in browser I get [object Object],[object Object],[object Object],[object Object],[object Object] as OUTPUT or undefined.
Your data looks like this:
[ //the array in data
{ //the first object, e. g. data[0]
"song":"Afreen Afreen", // song => data[0].song
"url":"http://hck.re/Rh8KTk",
"artists":"Rahat Fateh Ali Khan, Momina Mustehsan",
"cover_image":"http://hck.re/kWWxUI"
},
{
"song":"Aik Alif",
"url":"http://hck.re/ZeSJFd",
"artists":"Saieen Zahoor, Noori",
"cover_image":"http://hck.re/3Cm0IX"
},
{
"song":"Tajdar e haram",
"url":"http://hck.re/wxlUcX",
"artists":"Atif Aslam",
"cover_image":"http://hck.re/5dh4D5"
}]
So to loop over one can do
var limit=Math.max(data.length,100);//max displayed number
for(var i=0;i<limit;i++){
document.write(data[i].song+"<br>");
}
Whole code:
document.write("loading...");
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
var data= JSON.parse(xhr.responseText);
var limit=Math.max(data.length,100);
for(var i=0;i<limit;i++){
document.write(data[i].song+"<br>");
}
}
};
xhr.open('GET', 'http://starlord.hackerearth.com/sureify/cokestudio', true);
xhr.send(null);
You cannot write the whole song object to the document. You should map it first:
var songNames = data.map(function(item) { return item.song; });
This will give you an array of all the names (strings), which you can write to the document:
songNames.forEach(function(songName) {
document.write(songName + '<br>');
});
You need to use JSON.stringify; and if you plan to write to document I suggest wrapping in pre tags as well to retain string format.
let data = [
{
"song":"Afreen Afreen",
"url":"http://hck.re/Rh8KTk",
"artists":"Rahat Fateh Ali Khan, Momina Mustehsan",
"cover_image":"http://hck.re/kWWxUI"
},
{
"song":"Aik Alif",
"url":"http://hck.re/ZeSJFd",
"artists":"Saieen Zahoor, Noori",
"cover_image":"http://hck.re/3Cm0IX"
},
{
"song":"Tajdar e haram",
"url":"http://hck.re/wxlUcX",
"artists":"Atif Aslam",
"cover_image":"http://hck.re/5dh4D5"
}
];
document.write('<pre>'+ JSON.stringify(data, null, '\t') + '</pre>');
You need to stringify the object to make it readable.
<html>
<body>
<script type="text/javascript">
var requestURL = 'http://starlord.hackerearth.com/sureify/cokestudio';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function(){
var myjsondata = request.response;
showdata(myjsondata);
}
function showdata(data){
var song_name = data;
for (i = 0; i < 3; i++) {
document.write(JSON.stringify(song_name));
document.write("<br>");
}
}
</script>
</body>
</html>
The response from the request is an array of json objects and you are just trying to write the return object over and over again. You need to iterate over the returned data and output each object's value. Change your showdata function as:
function showdata(data){
for (i = 0; i < 3; i++) {
document.write(data[i].song);
document.write("<br>");
}
}

myObj.forEach(), isn't working

I'm trying store a XMLHttpRequest()'s results as a JSon String in an object, The data in the String is several arrays. I'm trying to then read through each array, in myObj.
Obviously, myObj.forEach() doesn't work, because myObj is an object, not an array or a list. How do I make it so I can itterate through myObj, and then use a forEach on each array?
Here is my current code
function getFile(){
var input = document.getElementsByName("json")[0];
var filename = input.value;
console.log(filename);
var xhr = new XMLHttpRequest();
xhr.open("GET", filename, true);
xhr.send(null);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var text = xhr.responseText;
document.getElementById("displayText").innerHTML = "";
var myObj = JSON.parse(text);
myObj.forEach(function(student) {...});
}
}
}
You can grab the keys of the Object into a list using Object.keys() and then iterate through them assuming they are all lists:
function getFile(){
var input = document.getElementsByName("json")[0];
var filename = input.value;
console.log(filename);
var xhr = new XMLHttpRequest();
xhr.open("GET", filename, true);
xhr.send(null);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var text = xhr.responseText;
document.getElementById("displayText").innerHTML = "";
var myObj = JSON.parse(text);
var keys = Object.keys(myObj);
keys.forEach(function(key) {
myObj[key].forEach(function(item) {...})
});
}
}
}

xmlHttp.responseText does not return data from json webservice

I am trying to retrieve data from json webservice.
if (xmlHttp.status == 200 || xmlHttp.status == 0)
{
var result = xmlHttp.responseText;
json = eval("(" + result + ")");
}
i"m getting nothing for the var result. When i replace the webservice with a text file which contains json object, then i can retrieve the json object as responseText. Please help
First things first... never ever, ever, ever use eval*. eval = evil.
How to use GET with AJAX...
try {
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
var url = "/uri/of/web-service?val1=Laura&val2=Linney" + Math.random();
var params = "val1=Laura&val2=Linney";
http.open("GET", url, true);
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// we have a response and this is where we do something with it
json = JSON.parse(http.responseText);
}
}
http.send();
How to use POST with AJAX...
try {
http = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e1) {
try {
http = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
this.xmlhttp = null;
}
}
var url = "/uri/of/web-service";
var params = "val1=Laura&val2=Linney";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// we have a response and this is where we do something with it
json = JSON.parse(http.responseText);
}
}
http.send(params);

Categories