In my webapp I have a page where I use getJSON to get data from server. Firebug shows that it get's JSON from server just the way it is supposed to, but no data is shown. What could be the problem? Here is what my code looks like:
$('#detailsPage').live('pageshow', function(event) {
var id = getUrlVars()["id"];
$.getJSON(serviceURL + 'getemployee.php?id='+id+'&callback=?', displayEmployee);
});
function displayEmployee(data) {
var employee = data.item;
$('#employeePic').attr('src', 'pics/' + employee.PIC);
$('#fullName').text(employee.NAME);
$('#employeeTitle').text(employee.TITLE);
$('#lisatieto').text(employee.INFO);
if (employee.puhelin_nro) {
$('#actionList').append('<li><h3>Soita puhelimeen</h3></li>');
$('#actionList').append('<li><h3>SMS</h3></li>');
}
$('#actionList').listview('refresh');
}
Console shows
employee is undefined
[Break On This Error]
$('#employeePic').attr('src', 'pics/' + employee.PIC);
This is the JSON response:
jQuery164008509381752724021_1336981793995({
"key": [
{
"PIC": "Tuntematon",
"NAME": "0",
"TITLE": "0",
"INFO": "0"
}
]
})
You need to use this
var employee = data.key[0];
Related
I need to access the nav for a specific date from the below JSON. eg : data[date="20-04-2022"].nav
How do I do it in Google Apps Script?
The standard JSON notation is not working.
{
"meta":{
"fund_house":"Mutual Fund",
"scheme_type":"Open Ended Schemes",
},
"data":[
{
"date":"22-04-2022",
"nav":"21.64000"
},
{
"date":"21-04-2022",
"nav":"21.69000"
},
{
"date":"20-04-2022",
"nav":"21.53000"
}
],
"status":"SUCCESS"
}
In your situation, I thought that it is required to retrieve the element including "date": "20-04-2022" from the array of data. So, how about the following sample script?
Sample script:
const obj = {
"meta": {
"fund_house": "Mutual Fund",
"scheme_type": "Open Ended Schemes",
},
"data": [
{
"date": "22-04-2022",
"nav": "21.64000"
},
{
"date": "21-04-2022",
"nav": "21.69000"
},
{
"date": "20-04-2022",
"nav": "21.53000"
}
],
"status": "SUCCESS"
};
const search = "20-04-2022";
const res = obj.data.find(({ date }) => date == search);
const value = res && res.nav;
console.log(value) // 21.53000
For example, if the search value is always found, you can use the following script.
const res2 = obj.data.find(({ date }) => date == search).nav;
Reference:
find()
Added 1:
From your following reply,
This looks like standard java script. Does not work in google apps script(script.google.com/home). Getting syntax error for this line : const res = obj.data.find(({ date }) => date == search);
I'm worried that you are not enabling V8 runtime. Ref If you cannot use V8 runtime, how about the following sample script?
Sample script:
var obj = {
"meta": {
"fund_house": "Mutual Fund",
"scheme_type": "Open Ended Schemes",
},
"data": [
{
"date": "22-04-2022",
"nav": "21.64000"
},
{
"date": "21-04-2022",
"nav": "21.69000"
},
{
"date": "20-04-2022",
"nav": "21.53000"
}
],
"status": "SUCCESS"
};
var search = "20-04-2022";
var res = obj.data.filter(function (e) { return e.date == search })[0];
var value = res && res.nav;
console.log(value) // 21.53000
Added 2:
From your following reply,
This looks like standard java script. Does not work in google apps script(script.google.com/home). Getting syntax error for this line : const res = obj.data.find(({ date }) => date == search);
I am trying to write a google apps script to fetch data from a url. But google seems to have its own way of handling the JSON data which I am unable to figure out. developers.google.com/apps-script/guides/services/…
I understood that your actual goal was to retrieve the value using Web Apps. If my understanding of your actual goal, how about the following sample script?
1. Sample script:
Please copy and paste the following script to the script editor and save the script.
function doGet(e) {
var search = e.parameter.search;
var obj = {
"meta": {
"fund_house": "Mutual Fund",
"scheme_type": "Open Ended Schemes",
},
"data": [
{
"date": "22-04-2022",
"nav": "21.64000"
},
{
"date": "21-04-2022",
"nav": "21.69000"
},
{
"date": "20-04-2022",
"nav": "21.53000"
}
],
"status": "SUCCESS"
};
var res = obj.data.filter(function (e) { return e.date == search })[0];
var value = res && res.nav;
return ContentService.createTextOutput(value);
}
I think that this sample script can be used with and without V8 runtime.
2. Deploy Web Apps.
In this case, please check the official document. Please set it as follows.
Execute as: Me
Anyone with Google account: Anyone
In this case, it supposes that you are using new IDE. Please be careful this.
3. Testing.
Please access to the URL like https://script.google.com/macros/s/{deploymentId}/exec?search=20-04-2022 using your browser. By this, the result value is returned.
`
I have a rails application where I have JSON data as shown below:
{"makes":[{"id":200347864,"name":"AM General","niceName":"am-general","models":[{"id":"AM_General_Hummer","name":"Hummer","niceName":"hummer","years":[{"id":3407,"year":1998},{"id":1140,"year":1999},{"id":305,"year":2000}]}]}]}
This is a very long list of car objects with multi-levels of nesting. Make, model, year, trim etc.
I want to send this JSON to javascript and populate my autofill drop down menu.
Previously, I was using a third-party API and the code looked like:
$( document ).ready(function() {
var prev ="https://xyz/makes";
var rest ="?fmt=json&api_key=";
var key = "<%= ENV['XYZ_API_KEY'] %>";
var net = prev+rest+key;
var options = [];
options.push("All");
var dictionary = {};
$.ajax({
url: net,
dataType: "json",
type: "get",
data: $(this).serialize()
}).done(function(data){
change_make(data);
change_model();
});
function change_make(data) {
for (var key in data["makes"]){
if (data["makes"].hasOwnProperty(key)){
var make = data["makes"][key];
options.push(make.name);
buffer = [];
// console.log(make.models);
for (var key2 in make.models){
// console.log(make.models[key2].name);
if (make.models.hasOwnProperty(key2)){
// console.log(make.models[key2].name);
buffer.push(make.models[key2].name);
}
}
dictionary[make.name] = buffer;
}
}
dictionary["All"] = ["All"]
// console.log(options);
$.each(options, function(key, value) {
$('#category')
.append($("<option></option>")
.attr("value", value.html_safe)
.text(value));
});
};
$('#category').on('change', function(){
console.log("change success");
change_model();
});
function change_model(){
var make = $('#category').find(":selected").text();
var models = dictionary[make];
// models.unshift("All");
$('#subcategory').empty();
$.each(models, function(key, value) {
$('#subcategory')
.append($("<option></option>")
.attr("value",value.html_safe)
.text(value));
});
}
$("#searchboxcontainer").delay(100).fadeIn(200);
});
Instead of using the ajax request, I want to use json string directly.
I wrote a helper method in application helper module as shown:
def edmunds_json
the_json_object
end
But when I am using it in javascript, its adding &gm characters and theobject comes out as:
{:makes=>[{:id=>200347864, :name=>"AM General",...
and the code is giving errors
Uncaught SyntaxError: Unexpected token :
When I am using escape in JSON, it's giving me the error on rails unexpected $undefined. expecting ').
The JSON object is using double quotes and I want to use it in my code. How should I proceed so > etc won't be added.
I think what you need to do is to first convert your Ruby Hash into json in your helper
def edmunds_json
the_json_object.to_json
end code here
Then in your view in a script tag do something like this
<script>
const object = <%= raw edmunds_json %>
console.log(typeof(object)) // => Object
</script>
Solved it by using:
<%= get_make_model_json.to_s.gsub("=>",":").html_safe %>; in javascript
where get_make_model_json is:
def get_make_model_json
JSON.parse(
'{
"makes": [{
"id": 200347864,
"name": "AM General",
"niceName": "am-general",
"models": [{
"id": "AM_General_Hummer",
"name": "Hummer",
"niceName": "hummer",
"years": [{
"id": 3407,
"year": 1998
}, {
"id": 1140,
"year": 1999
}, {
"id": 305,
"year": 2000
}]
}]
},...
end
I know this question gets asked in different ways but I am struggling to wrap my head around how to handle the data returned from an API URI and hoping to get a clearer idea of how to properly use it.
I am practicing APIs and decided to make a simple weather app that gets data from openweathermap.com
An example URI is http://api.openweathermap.org/data/2.5/weather?q=Los+Angeles&APPID=myApiKey
I concat this data using an input on my page that fills in whatever city or zip you type in and printing the full path as a link works just fine. But when I try to parse the data from this URI I get an error
Uncaught SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
at getWeather (index.js:25)
at HTMLButtonElement.onclick
I am trying to break down the data inside of this API data so I can appropriately display things like temp, wind, humidity etc.
This is the code that I wrote to test if I am properly getting the data.
// Set API variables
const api = "http://api.openweathermap.org/data/2.5/weather?q=";
const apiKey ="myAPIKey";
// Set City and Units
let unitType = "imperial";
let units = "&units=" + unitType;
function setup() {
var button = document.getElementById('submit');
button.click = getWeather();
}
function getWeather() {
let city = document.getElementById('city').value;
let fullPath = api + city + "&APPID=" + apiKey + units;
console.log(city);
//document.getElementById('weatherData').innerHTML='' + city + '';
let data = fullPath;
let obj = JSON.parse(data);
document.getElementById('weatherData').innerHTML = obj.main.temp;
}
the getWeather() function is called when you click the submit button on the page which looks like:
<!doctype html>
<html>
<head></head>
<body>
<input type="text" id="city" placeholder="Enter a city" />
<button onclick="getWeather()" id="submit">Submit</button>
<div id="weatherData" style="background: #ccc; padding: 20px; margin-top: 25px;">
</div>
<script src="index.js"></script>
</body>
</html>
What am I doing wrong? I have never worked with APIs before so please forgive me if I look very ignorant here. When I had the program just print a concatenated URL (linking to the URI itself) on the screen it worked, but now that I'm trying to actually extract data I get the error from above.
Edit here's an example of the API data returned:
{
"coord": {
"lon": -96.81,
"lat": 32.78
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04d"
}
],
"base": "stations",
"main": {
"temp": 295.15,
"pressure": 1016,
"humidity": 78,
"temp_min": 294.15,
"temp_max": 296.15
},
"visibility": 20921,
"wind": {
"speed": 4.1,
"deg": 180
},
"clouds": {
"all": 100
},
"dt": 1491835980,
"sys": {
"type": 1,
"id": 2596,
"message": 0.0099,
"country": "US",
"sunrise": 1491825755,
"sunset": 1491872065
},
"id": 4684888,
"name": "Dallas",
"cod": 200
}
let fullPath = api + city + "&APPID=" + apiKey + units; // fullPath is a string representing an URL
let data = fullPath; // data is a string representing an URL
let obj = JSON.parse(data); // You try to parse an URL, not JSON
You try to parse an URL, so it doesn't work. Make a XHR request on this URL to get your JSON data.
Edit:
To request a remote JSON file, use the fetch API (include a polyfill if your browser doesn't implement fetch):
fetch('/data.json')
.then(function(response) {
return response.json();
}).then(function(json) {
console.log('parsed json', json);
}).catch(function(ex) {
console.log('parsing failed', ex);
})
I have a function which loops through a list of json objects. It actually works, but it gives me this error: "Uncaught TypeError: Cannot read property 'values' of undefined" pointing to this line:
var resValues = result.values;
My code is:
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
function onLinkedInAuth() {
var cpnyID = 2414183; //LinkedIn's testDevCo
IN.API.Raw("/companies/" + cpnyID + "/updates?event-type=status-update&start=0&count=10&format=json")
.result(displayUpdates);
}
function displayUpdates(result) {
var resValues = result.values;
for (var i in resValues) {
var share = resValues[i].updateContent.companyStatusUpdate.share;
console.log(share);
}
}
What do I need to change in order to fix this error?
The json looks something like this:
{
"values": [{
"updateContent": {
"companyStatusUpdate": {
"share": {
"content": {
"description": "Test description",
"eyebrowUrl": "http://linkd.in/…",
"shortenedUrl": "http://linkd.in/…",
"submittedImageUrl": "http://m.c.lnkd.licdn.com/…",
"submittedUrl": "http://linkd.in/…",
"thumbnailUrl": "https://media.licdn.com/…",
"title": "Best Advice: Take Jobs Others Don't Want"
}
}
}
}
}]
}
Thanks a lot in advance.
Turns out that this errors appeared because I was listing displayupdates further up in the head section where the api key is entered: I removed it so I only have:
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: xxxxxxxxxxxxxxxx
**onLoad: onLinkedInLoad, onLinkedInAuth**
authorize: true
</script>
Below is the structure of JSON which I use to query an API
"order_items": [
{
"menu_item_id": "VD1PIEBIIG",
"menu_item_name": "Create Your Own",
"modifiers": [
{
"modifier_id": "6HEK9TXSBQ",
"modifier_name": "Shrimp"
}
],
"quantity": "1",
"total": 15.99,
"variant_id": "TXDOR7S83E",
"variant_name": "X-Lg 18\""
}
]
Now I want to call this API from an HTML page using Javascript(Using HTML elements like forms and drop down menus etc). I want to create a Javascript object with proper structure and then convert it to JSON using "stringify" function. But I am not able to create the Javascript object. Can anyone help with this?
Like i want to have the following structure
obj.order_items[0].menu_item_id="VD1PIEBIIG";
obj.order_items[0].menu_item_name="Create Your Own";
obj.order_items[0].modifiers[0].modifier_id="6HEK9TXSBQ";
and so on.
var jsonToSend = { "order_items": [ ] };
// then for each order item
var orderItem = { "menu_item_id": <whatever>,
"menu_item_name": <whatever>,
"quantity": <whatever>,
"total": <whatever>,
"variant_id": <whatever>,
"variant_name": <whatever>,
"modifiers": []
};
// then for each modifier
var modifier = { "modifier_id": <whatever>, "modifier_name": <whatever> };
orderItem.modifiers.push(modifier);
jsonToSend.order_items.push(orderItem);
JSON.stringify(jsonToSend);
Well there are a couple of ways to do this.
Manually create the Json object to send from the HTML elements:
$.ajax({
type: "POST",
url: "some.php",
data: new {"order_items": [
{
"total": $('total').Val(),
"variant_id": $('variant_id').Val(),
"variant_name": $('variant_name').Val()
}
]})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
You could use a great framework like KnockoutJs, this will keep your JSON object up to date with your form, so that you don't have to do it manually. When you are ready you just submit your original json back to the server.
See this basic example on JsFiddle
var ClickCounterViewModel = function() {
this.numberOfClicks = ko.observable(0);
this.registerClick = function() {
this.numberOfClicks(this.numberOfClicks() + 1);
};
this.resetClicks = function() {
this.numberOfClicks(0);
};
this.hasClickedTooManyTimes = ko.computed(function() {
return this.numberOfClicks() >= 3;
}, this);
};
ko.applyBindings(new ClickCounterViewModel());
You can use any number of plugins to Serialize the form, but the problem is getting the JSON structure just right.
See SerializeArray
$( "form" ).submit(function( event ) {
console.log( $( this ).serializeArray() );
event.preventDefault();
});