JSON Object Access Value - javascript

This is my JSON response:
{
"2f2EdLjYHcTx4APbgnlvE2SCXQb2": {
"name": "test",
"latitute": 7.4866174,
"longitute": 80.3637889
},
"pJua8KSpMwSXiSlWJcDE4sEkOuZ2": {
"name": "akalanka",
"latitute": 7.4866198,
"longitute": 80.3638016
}
}
How can i access name, latitude and longitute in JavaScript?
I tried using this method, it shows data but i can't access the properties I need:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://localhost:3000/get/json", false );
xmlHttp.send();
var data=xmlHttp.responseText;
var x=[];
x=JSON.parse(xmlHttp.responseText);
// x=data.length;
console.log(x);
// latitute=x.latitute;
// longitute=x.longitute;
z=15;
myMap();
}

Two problems in the code:
1) You are using xmlHttp incorrectly.
You are sending the request but parsing the result directly (without waiting for the request to succeed).
xmlHttp.open( "GET", "http://localhost:3000/get/json", false );
xmlHttp.send();
xmlHttp.onload = function () {
// Request finished. Do processing here.
};
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/send
2) You need to use the key to access the 'latitute'.
Object.keys(x).forEach(field => {
console.log(x[field].latitute);
console.log(x[field].longitute);
});
So it should look like this:
xmlHttp.open( "GET", "http://localhost:3000/get/json", false );
xmlHttp.send();
xmlHttp.onload = function () {
var x = JSON.parse(xmlHttp.responseText);
Object.keys(x).forEach(field => {
console.log(x[field].latitute);
console.log(x[field].longitute);
});
};

First, please confirm that you already get responseText by using onreadystate method.
After that, please try with this.
var responseText = `{"2f2EdLjYHcTx4APbgnlvE2SCXQb2":{"name":"test","latitute":7.4866174,"longitute":80.3637889},"pJua8KSpMwSXiSlWJcDE4sEkOuZ2":{"name":"akalanka","latitute":7.4866198,"longitute":80.3638016}}`;
var x = JSON.parse(responseText);
console.log(x);
Object.keys(x).forEach(field => {
console.log(x[field].name);
});

Beware your properties are misspelled longitute, latitute... te? Should be de
I'd convert the nonstandard UID-as-keys to a simple Array.
Quick example using fetch API:
const myMap = (data) => {
console.log(`lat:${data.latitute}, lng:${data.longitute}`)
};
const fetchMapData = async () => {
const response = await fetch('https://jsbin.com/mijopocunu/js');
const json = await response.json();
const dataArr = Object.keys(json).map(k => (json[k].id = k, json[k]));
dataArr.forEach(myMap);
};
fetchMapData();

Related

How to preload JSON link?

I've got a function that needs to call a link (JSON format), the fact is that I would like to be able to preload this link to smooth and reduce the operation time when calling the function.
onSelectionChanged: function (selectedItems) {
selectedItems.selectedRowsData.forEach(function(data) {
if(data) {
colorMe(data.target)
}
});
}
function colorMe(item){
globalItem = item;
request('http://blablabla/?format=json',findMaterial);
};
function findMaterial(data){
jq310.each(data, function(table) {
if (data[table].identifier == globalItem){
globalData = data[table]
request('http://another-blablabla/?format=json',findMatchArea);
};
});
};
function findMatchArea(areas){
jq310.each(areas, function(area) {
blablabla
The request function that I built just look if the link as been already called, so it's reloading it if true. And also send data from the link to the called function.
If you'r looking to load a static json file you should concider loading it on the top of your file. To do so you should store the datas in a global variable like that :
let datas;
request('http://blablabla/?format=json', (data) => {
datas = data
});
onSelectionChanged: function (selectedItems) {
selectedItems.selectedRowsData.forEach(function(data) {
if(data) {
globalItem = data.target;
findMaterial();
}
});
}
function colorMe(item){
globalItem = item;
};
function findMaterial(){
const data = datas;
jq310.each(data, function(table) {
if (data[table].identifier == globalItem){
globalData = data[table]
request('http://another-blablabla/?format=json',findMatchArea);
};
});
};
I finally found a way to do it properly, here it is :
var mylink = 'https://fr.wikipedia.org/wiki/JavaScript';
function preloadURL(link){
var xhReq = new XMLHttpRequest();
xhReq.open("GET", link, false);
xhReq.send(null);
var jsonObject = JSON.parse(xhReq.responseText);
return jsonObject;
};
jsonObjectInv = preloadURL(mylink);
And I just point to my json variable to parse it (really faster)
function colorMe(item){
globalItem = item;
findMaterial(jsonObjectInv);
};
Problem solved

Initialize variable after ajax callback

I'm looking for a way to initialize a var after an ajax call. The problem is that the ajax call is in an another file.
Here is my code :
file1.js
$(document).ready(function () {
getKanbans();
});
function getKanbans() {
var kanbans = RequestSender.getKanbans();
console.log(kanbans); // print undefined
}
RequestSender.js
class RequestSender {
static getKanbans() {
$.ajax({
url: './ajax/select_kanbans.php',
type: 'GET',
success: RequestSender.initKanbanList
});
}
static initKanbanList(data) {
var result = JSON.parse(data);
var kanbans = [];
for (var i = 0; i < result.kanbans.length; ++i) {
var currentKanban = result.kanbans[i];
kanbans.push(new Kanban(currentKanban['Name'], currentKanban['Status']))
}
console.log(kanbans); // correctly displayed
return kanbans;
}
}
I just use jQuery, all my files are included. I think that the problem come from the fact that ajax is async but I don't know how to fix that.
in your example ajax call started but kanbans still undefined
function getKanbans() {
//ajax call started but kanbans still undefined
var kanbans = RequestSender.getKanbans();
console.log(kanbans); // print undefined
}
so you should complete execution after ajax call finished you can do that with the help of promises
for more information Check this
function getKanbans(url) {
var promiseObj = new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("xhr done successfully");
var response = xhr.responseText;
var responseJson = initKanbanList(response);
resolve(responseJson);
} else {
reject(xhr.status);
console.log("xhr failed");
}
} else {
console.log("xhr processing going on");
}
}
console.log("request sent succesfully");
});
return promiseObj;
}
function initKanbanList(data) {
var result = JSON.parse(data);
var kanbans = [];
for (var i = 0; i < result.kanbans.length; ++i) {
var currentKanban = result.kanbans[i];
kanbans.push(new Kanban(currentKanban['Name'], currentKanban['Status']))
}
console.log(kanbans); // correctly displayed
return kanbans;
}
$(document).ready(function () {
// to call it
getKanbans('./ajax/select_kanbans.php').then(function (kanbans) {
console.log(kanbans);
}, function (error) {
console.log(error);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
This is called modules in javascript. You can implement them using link tags directly. But you are much better served by libraries like RequireJS and others. Then you can do things like:
require(['./RequestSender'], function (RequestSender) {
var rs = new RequestSender();
... //whatever
});
Here is a good SO question that explains modules well: How do I include a JavaScript file in another JavaScript file?

How to access a JSON array directly from url

I am new to javascript and I have a Json Array in a url like below;
[{"year":2015,"month":4,"day":1,"num":0,"time":"2015-04-01","hour":0,"zone":3,"state1":2137,"state2":249,"state3":1810,"state4":30,"state5":0},....]
I want to access the state1 value and assign that value to the variable which I have.How can I do that?(Is parsing necessary or are there any methods there that we can directly access the JSON object in the URL).I am sorry if I asked anything wrong.
You can use jQuery getJSON() function :
$.getJSON(' localhost:8080/dataurl', function(data) {
//data is the JSON string
var jsonObj = JSON.parse(data);
});
Now, Below are the methods to parse the jsonObj to get the state1.
Using array map() method :
var jsonObj = [
{
"year":2015,
"month":4,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2137,
"state2":249,
"state3":1810,
"state4":30,
"state5":0
},
{
"year":2016,
"month":12,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2474,
"state2":250,
"state3":1811,
"state4":31,
"state5":0
}
];
var state1arr = jsonObj.map(function(item) {
return item.state1;
});
console.log(state1arr);
using for...in loop :
var jsonObj = [
{
"year":2015,
"month":4,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2137,
"state2":249,
"state3":1810,
"state4":30,
"state5":0
},
{
"year":2016,
"month":12,
"day":1,
"num":0,
"time":"2015-04-01",
"hour":0,
"zone":3,
"state1":2474,
"state2":250,
"state3":1811,
"state4":31,
"state5":0
}
];
var state1arr = [];
for (var i in jsonObj) {
state1arr.push(jsonObj[i].state1);
}
console.log(state1arr);
The data you have is array of objects and you need to loop to access each object and access the key using dot notation
Like this,
var app=[{"year":2015,"month":4,"day":1,"num":0,"time":"2015-04-01","hour":0,"zone":3,"state1":2137,"state2":249,"state3":1810,"state4":30,"state5":0}];
for(var i of app)
{
console.log(i.state1);
}
Just use the following JS Code:
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
You can now use the function to get the JSON contents from the url:
getJSON("<URL>").then(function(data) { // Replace <URL> With your URL
var jsondata = data.result; //store result in variable
// Your code here....///
/// Now you can access the json's data using jsondata variable: //
// jsondata[0].year will have the value of year key, jsondata[0].month will have month key and so on.... //
}, function(status) { //error detection....
alert('Something went wrong.');
});

Save Json in Javascript variable

I'm studying javascript these days and I have question. I have variable that contain an url. I would like to save the content of the url pointed by my variable in another variable...
The first variable is something like:
var Link = "http://mysite.com/json/public/search?q=variabile&k=&e=1";
If I open the link I see something like:
{
"count": 1,
"e": 1,
"k": null,
"privateresult": 0,
"q": "gabriel",
"start": 0,
"cards": [
{
"__guid__": "cdf8ee96538c3811a6a118c72365a9ec",
"company": false,
"__title__": "Gabriel Butoeru",
"__class__": "entity",
"services": false,
"__own__": false,
"vanity_urls": [
"gabriel-butoeru"
]
}
]
}
How can I save the json content in another javascript variable?
You would need a simple AJAX request to get the contents into a variable.
var xhReq = new XMLHttpRequest();
xhReq.open("GET", yourUrl, false);
xhReq.send(null);
var jsonObject = JSON.parse(xhReq.responseText);
Please note that AJAX is bound by same-origin-policy, in case that URL is different this will fail.
You can use like this
var savings_data = JSON.stringify(your_json_object);
You can save json as object in this way
Reference : Json
var obj = {};
obj.name = "test";
obj.no = "1234";
I think this might help you, using jQuery... :)
$.ajax({
beforeSend: function() { DO HERE WHATEVER }, //Show spinner
complete: function() { DO HERE WHATEVER }, //Hide spinner
type: 'POST',
url: Link,
dataType: 'JSON',
success: function(data){
var data = data;
OR IF YOU WANT SEPARATE THE VALUES...
var count = data.count;
var e = data.e;
var k = data.k;
...
}
});
This example considers the state of the request and will allow you to access the data from the JSON format using the dot operator.
var request = new XMLHttpRequest();
request.open("GET", "mysite.com/json/public/search?q=variabile&k=&e=1", true);
request.setRequestHeader("Content-type", "application/json");
request.send();
request.onreadystatechange = function(){
if(request.ready == 4 && request.readyState == 200){
var response = request.responseText;
var obj = JSON.parse(response);
alert(obj.count); // should return the value of count (i.e Count = 1)
alert(obj.e); // should return the value of e (i.e. e = 1)
var count = obj.count; //store the result of count into your variable
var e = obj.e; //store the result of e into your variable
//...and so on
}
}

Use jQuery to replace XMLHttpRequest

I am quite new to JavaScript libraries. I wanted to replace my current code with jQuery. My current code looks like this:
var req;
function createRequest() {
var key = document.getElementById("key");
var keypressed = document.getElementById("keypressed");
keypressed.value = key.value;
var url = "/My_Servlet/response?key=" + escape(key.value);
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open("Get", url, true);
req.onreadystatechange = callback;
req.send(null);
}
function callback() {
if (req.readyState == 4) {
if (req.status == 200) {
var decimal = document.getElementById('decimal');
decimal.value = req.responseText;
}
}
clear();
}
I wanted to replace my code with something a little friendlier like jQuery's
$.get(url, callback);
However it doesn't call my callback function.
Also I would like to call a function called createRequest continuously. Does jQuery have a nice way of doing that?
­­­­­­­­­­­­­­­­­­­­­­­
$.get(url, {}, callback);
should do the trick. Your callback could be simplified like this:
function callback(content){
$('#decimal').val(content);
}
Or even shorter:
$.get(url, {}, function(content){
$('#decimal').val(content);
});
And all in all I think this should work:
function createRequest() {
var keyValue = $('#key').val();
$('#keypressed').val(keyValue);
var url = "/My_Servlet/response";
$.get(url, {key: keyValue}, function(content){
$('#decimal').val(content);
});
}
Take out the readyState and status checks. jQuery only calls your callback upon success. Your callback is supplied the arguments (data, textStatus), so you should use data instead of req.responseText.
window.setTimeout() as suggested by another answer won't do what you want - that only waits and then calls your function once. You need to use window.setInterval() instead, which will call your function periodically until you cancel it.
So, in summary:
var interval = 500; /* Milliseconds between requests. */
window.setInterval(function() {
var val = $("#key").val();
$("#keypressed").val(val);
$.get("/My_Servlet/response", { "key": val }, function(data, textStatus) {
$("#decimal").val(data);
});
}), interval);
I don't think jQuery implements a timeout function, but plain old javascript does it rather nicely :)
According to the docs, jQuery.get's arguments are url, data, callback, not url, callback.
A call to JavaScript's setTimeout function at the end of your callback function should suffice to get this to continually execute.
There's no need to set the GET parameters on the URL, jQuery will set them automatically. Try this code:
var key = document.getElementById("key");
[...]
var url = "/My_Servlet/response";
$.get (url, {'key': key}, function (responseText)
{
var decimal = document.getElementById ('decimal');
decimal.value = responseText;
});
In the end I guess it was added the type. This seems to work for me.
function convertToDecimal(){
var key = document.getElementById("key");
var keypressed = document.getElementById("keypressed");
keypressed.value = key.value;
var url = "/My_Servlet/response?key="+ escape(key.value);
jQuery.get(url, {}, function(data){
callback(data);}
, "text" );
}
function callback(data){
var decimal = document.getElementById('decimal');
decimal.value = data;
clear();
}
Thanks Everyone for the help. I'll vote you up.

Categories

Resources