Access json string in JavaScript - javascript

I have a String called json which has ArrayList values. I used Gson to convert the arraylist to json. I am passing the json to a javascript from servlet as a response in POST.
I get the response in js as ["1.343","73.6544","32.6454","34.453","43.565","23.454"]. How to access these values in js with a variable individually(these are location coordinates). I want to use these values to display the location in my map.
How do i access these values in js. The value obtained in js is a string which contains arraylist. I used gson to convert to string.
This is js:
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var data = xhr.responseText;
data.toString();
alert(data);
}
}
xhr.open('POST', 'GetLocationFromDB', true);
xhr.send(null);
</script>
The data is value from servlet.
SErvlet:
String json = new Gson().toJson(arraylist);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);

Parse the response to Json and you will have access to the elements
var json = JSON.parse(data);
Read more on JSON.parse here. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
As a simple test to should how JSON.parse works.
var x = JSON.parse('["1.343","73.6544","32.6454","34.453","43.565","23.454"]');
alert(x[0]) // alerts with 1.343
Here is what you should have.
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var json = JSON.parse(xhr.responseText);
console.log(json);
//or if you like alerts
alert(json);
}
}
xhr.open('POST', 'GetLocationFromDB', true);
xhr.send();

You have to parse your data.
JSON.parse() for parsing a string of JSON text into a javascript Object and JSON.stringify for turing a Javascript object into JSON text.

Related

How do I get a specific key value from JSON object

This is my first time using any kind of APIs, and I'm just starting out in JS. I want to get the status of a server within a server hosting panel, to do this I need to log in (API/Core/Login), get a the value of a key called sessionID, then send that value to /API/Core/GetUpdates to get a response. When trying to pass the sessionID to GetUpdates, it sends undefined instead of the sessionID, I'm guessing I'm doing something wrong when trying to reference the key value. Here's my code:
var loginurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/Login";
var loginRequest = new XMLHttpRequest();
loginRequest.open("POST", loginurl);
loginRequest.setRequestHeader("Accept", "text/javascript");
loginRequest.setRequestHeader("Content-Type", "application/json");
loginRequest.onreadystatechange = function() {
if (loginRequest.readyState === 4) {
console.log(loginRequest.status);
console.log(loginRequest.responseText);
}
};
var logindata = '{"username":"API", "password":"password", "token":"", "rememberMe":"true"}';
loginRequest.send(logindata);
var statusurl = "https://proxyforcors.workers.dev/?https://the.panel/API/ADSModule/Servers/83e9181/API/Core/GetUpdates";
var statusreq = new XMLHttpRequest();
statusreq.open("POST", statusurl);
statusreq.setRequestHeader("Accept", "text/javascript");
statusreq.setRequestHeader("Content-Type", "application/json");
statusreq.onreadystatechange = function() {
if (statusreq.readyState === 4) {
console.log(statusreq.status);
console.log(statusreq.responseText);
}
};
var statusdata = `{"SESSIONID":"${loginRequest.responseText.sessionID}"}`; // Line I'm having problems with
statusreq.send(statusdata);
console.log(loginRequest.responseText.sessionID)
Here's the response of /API/Core/Login
{"success":true,"permissions":[],"sessionID":"1d212b7a-a54d-4e91-abde-9e1f7b0e03f2","rememberMeToken":"5df7cf99-15f5-4e01-b804-6e33a65bd6d8","userInfo":{"ID":"034f33ba-3bca-47c7-922a-7a0e7bebd3fd","Username":"API","IsTwoFactorEnabled":false,"Disabled":false,"LastLogin":"\/Date(1639944571884)\/","GravatarHash":"8a5da52ed126447d359e70c05721a8aa","IsLDAPUser":false},"result":10}
Any help would be greatly appreciated, I've been stuck on this for awhile.
responseText is the text representation of the JSON response.
Either use JSON.parse(logindata.responseText) to get the JSON data or use logindata.responseJSON

How to remove unwanted characters from JSON request

I am new to javascript.
I am facing this issue where I get [{"_id":1}] as my results.
Does anyone know how can I get 1 as my output?
This is my code, I am calling it from a database.
function getaccountid() {
var accID = new XMLHttpRequest();
accID.open('GET', "http://127.0.0.1:8080/account" + "/" + sessionStorage.getItem("username"), true);
accID.setRequestHeader("Content-Type", "application/json");
accID.send(JSON.parse);
accID.onload = function () {
sessionStorage.setItem("accountId", accID.response)
}
}
That response type is a JSON formatted string, it's a standard response type, not an issue. To read the value you need to parse the result from a JSON string to an array of objects, then access it.
Also note that you need to remove the JSON.parse reference within the send() call and define the load event handler before you send the request. Try this:
function getaccountid() {
var accID = new XMLHttpRequest();
accID.addEventListener('load', function() {
let responseObject = JSON.parse(this.responseText);
sessionStorage.setItem("accountId", responseObject[0]['_id']);
console.log(responseObject[0]['_id']); // = 1
});
accID.open('GET', "http://127.0.0.1:8080/account/" + sessionStorage.getItem("username"), true);
accID.setRequestHeader("Content-Type", "application/json");
accID.send();
}

can not convert JSON to object

First of all I have searched the internet for a solution to my problem.
I have found several sites that can parse my JSON and tell me that it's valid. I knew that beforehand since it originates from my SQL Server.
But when calling JSON.parse(...) with the following json, I get a string back not a object!
My code so far:
function GetConfig(url) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false);
xhr.send(null);
if (xhr.status === 200)
return JSON.parse(xhr.responseText);
else
return null;
};
/*
xhr.responseText returns this JSON:
{"graphSettings":{"Caption":"TEST","Min":2.850000000000000e+001,"Max":2.950000000000000e+001}}
*/
function GenerateHighChart(ressponse) {
var data = GetConfig('/api/Settings/Powerlog/Temperatures');
}
But when trying to access data as a object I get an error since data is still a string
var a = data.graphSettings.min;
UPDATE
I believe the problem is in my API
So here is my controller:
[Produces("application/json")]
[Route("api/Settings")]
public class APIGetSettings : Controller
{
private string InternalGetJson(string commandText, params object[] parameters)
{
var json = GetJson(commandText, parameters);
return json.Replace("[", "").Replace("]", "");
}
private string GetSettingFromName(string name) => InternalGetJson("select * from fn_GetVisualSettings(#0) for json path", name);
[Route("Powerlog/Temperatures")]
public IActionResult Powerlog_Temperatures() => new JsonResult(GetSettingFromName("Powerlog/Temperatures"));
}
/*
JSON returned from GetSettingFromName
{"graphSettings":{"Caption":"TEST","Min":2.850000000000000e+001,"Max":2.950000000000000e+001}}
*/
in my Javascript if I change GetConfig to
if (xhr.status === 200)
return JSON.parse(xhr.responseJSON);
else
return null;
responseJSON is undefined
** UPDATE **
I found the bug. the problem is the text returned from my API
I get this :
"{\"graphSettings\":{\"Caption\":\"TEST\",\"Min\":2.850000000000000e+001,\"Max\":2.950000000000000e+001}}"
but expected this:
"{"graphSettings":{"Caption":"TEST","Min":2.850000000000000e+001,"Max":2.950000000000000e+001}}"
I'll create a new QUESTION
This is working:
var x = {"graphSettings":{"Caption":"TEST","Min":2.850000000000000e+001,"Max":2.950000000000000e+001}}
console.log(x.graphSettings.Min);
Please log/debug the xhr.responseText and see whats there.
If you have any error, remember to post it here as well.

I'm getting undefined when accessing JSON attribute

I'm using Parse Server, and in the Cloude Code, before save, I want to get a json from an api.
I'm using XMLHttpRequest to get a json, and here's the result of the json formatted:
This is my code to get the json:
var getJSON = function(url, requisicaoAceita, requisicaoFracassou) {
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
if(xhr.status!=200){
requisicaoFracassou(xhr.responseText);
}else{
requisicaoAceita(xhr.responseText);
}
};
xhr.send();
};
getJSON(url,
function(xhr){
var resultado = xhr;
console.log(resultado);
console.log(resultado.result);
},
function(xhr){
console.log("Error");
}
);
In the first output console.log(resultado) I get the result correctly, but in the second console.log(resultado.result) i get undefined, why is that?
Thanks :)
You did use .responseText instead of .response which would take into account the chosen responseType. Your resultado is still a JSON string, not an object with a result property
Thanks for help-me Shubham Khatri
parse the result before using
console.log(JSON.parse(resultado).result);
After doing this, worked!
var resultado = JSON.parse(xhr);
console.log(resultado.result);

cannot pass a javascript object to php via ajax

I've created a new array in javascript and I'm adding values to it indexes from a function an then passing the array to the ajaxCall function were I try to convert it to json and send it to a php file via ajax, but the variable json is allways empty. I've been reading a lot about how to send javascript objects json_encoded via ajax and looks like this is the way to do it, but obviously I haven't readed enought or there is something I've been missing. Anycase I'm newbie in javascript and any help would be apreciated.
function createArray()
{
var advancedFormVars = new Array();
advancedFormVars['checkbox1'] = document.getElementById('OfferID').value;
advancedFormVars['checkbox2'] =document.getElementById('offerName').value;
AjaxCall(advancedFormVars);
}
function AjaxCall(advancedFormVars){
var json = new Array();
json = JSON.stringify(advancedFormVars); //in debuger it shows me this as content of json variable--> [] but advancedFormVars is not empty
$.ajax({
url : 'AL_loadForm.php',
type : 'POST',
data : {
json : json
},
dataType:'json',
success : function(data) {
alert(data);
}
...
You are trying to use your array as a hash, so the values are not being set..
Instead of setting
var advancedFormVars = new Array();
Try setting
var advancedFormVars = {};
Example
JS:
var advancedFormVars = {};
advancedFormVars['checkbox1'] = 'valueA';
advancedFormVars['checkbox2'] = 'valueB';
var json = JSON.stringify(advancedFormVars);
console.log(json); //{"checkbox1":"valueA","checkbox2":"valueB"}
PHP
<?php
$json = '{"checkbox1":"valueA","checkbox2":"valueB"}';
$obj = json_decode($json);
var_dump($obj);
/*
object(stdClass)#1 (2) {
["checkbox1"]=>
string(6) "valueA"
["checkbox2"]=>
string(6) "valueB"
}
*/
?>
If all you have are two smaller arguments, I'd keep it simple and make an http get request. Encode your arguments if neccessary.
var url = "http://wherever.com/something.php?arg1=";
url += document.getElementById('OfferID').value;
url += "&arg2=" + document.getElementById('offerName').value;
httpGetAsync(url, returnMethod);
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}

Categories