Using javascript/html to grab one piece of data from JSON result - javascript

Before I start, I'm complete beginner and I hope I'm not misusing terms when I ask my question.
I'm starting off writing an HTML5/Javascript application using Intel XDK to query barcodes of videos games from an online api, and I only need one piece of the JSON result (the title of the game) to then go on and use within my app.
The JSON result looks like this:
{"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}
All I want to use in my app is that very first 'productname' entry.
The JSON is from an api provider I have an account with so it's on a remote URL for examples sake we'll call the URL: http://JsonIs.here
I want to be able to query the JSON URL and return "The Elder Scrolls V: Skyrim" as a string which I can then go on to use elsewhere in the application.
I've got my barcode scanning working, I can create the GET request URL already, I just don't know where to start calling that URL and then returning the small piece of information I need.

You can use jQuery's $.getJSON for this. The method returns a promise which has a nice easy-to-understand API.
var productName;
$.getJSON('http://JsonIs.here').then(function (data) {
productName = data[0].productname;
});
A couple of things to note here. 1) getJSON is an asynchronous process, so productName won't be immediately available, so you might have to restructure your code a little to account for this. You can't, for example do this:
var productName;
$.getJSON('http://JsonIs.here').then(function (data) {
productName = data[0].productname;
});
console.log(productName); // undefined
You may find this article useful as it covers how to return a value from an async process in depth.
2) getJSON automatically parses the JSON so you don't have to which is why, in the example, I've called the argument data and not json to save confusion.

To simulate you getting your JSON
var getJSON = function(){
return '{"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}';
};
a function that gets the JSON and creates an array that holds all your productnames
var getProductName = function(){
// get the JSON_string ;)
var JSON_string = getJSON();
// convert it to an obj.
var JSON_obj = JSON.parse(JSON_string);
//create something to store your data in, you don't need to do this ofcourse
var r_productNames = [];
for(var key in JSON_obj){
if(JSON_obj.hasOwnProperty(key)){
r_productNames.push(JSON_obj[key].productname);
}
}
// et voila, you have an array of all the productnames, returned by your request.
console.log(r_productNames);
};
It works for me ;)

Json comes with a key value pair and the indexing starts with 0. Hence json[0] that means json in first index. json[0].productname here productname is the key which will give the value in return
var json = {"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}
alert(json[0].productname);

Try using ajax
$.ajax({
type: 'GET',
url: 'http://JsonIs.here',
dataType: "json",
success: function(data) {
console.log(data[0].productname)
},
error: function(data) {
}
});
Using ajax you can try to get the data from the url and you can get the data in the success of the request

Here you go. However I find "0" as key in your JSON response somewhat not seen till today. It is better practice to start of with a character.
Your JSON response have one object. You can access the element in the object by index. Here on 0th index you have your data. The reason we are accessing it as a[0].key where key represent name of key you want to access from the object.
This is how you can get the data from JSON and use it in your application to achieve rest of your functionality as per your question.
var a = {"0":{"productname":"The Elder Scrolls V: Skyrim","imageurl":"http://ecx.images-amazon.com/images/I/413Gdr3FzqL._SL160_.jpg","producturl":"","price":"14.00","currency":"USD","saleprice":"","storename":"N/A"},"1":{"productname":"Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41QbF1Vg5KL._SL160_.jpg","producturl":"","price":"18.00","currency":"USD","saleprice":"","storename":"N/A"},"2":{"productname":"Bethesda Softworks Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41X97hqaJwL._SL160_.jpg","producturl":"","price":"23.95","currency":"USD","saleprice":"","storename":"N/A"},"3":{"productname":"BETHESDA SOFTWORKS 11763 / Skyrim X360","imageurl":"http://ecx.images-amazon.com/images/I/41IaEzP-6pL._SL160_.jpg","producturl":"","price":"34.00","currency":"USD","saleprice":"","storename":"N/A"}}
a[0].productname;

Related

Ajax Parameter Being Received as {string[0[} in MVC Controller

First of all, I have never successfully built an AJAX call that worked. This is my first real try at doing this.
I am working on building a function to update existing records in a SQL database. I am using ASP.NET Core (.NET 6) MVC but I also use JavaScript and jQuery. I cannot have the page refresh, so I need to use ajax to contact the Controller and update the records.
I have an array that was converted from a NodeList. When I debug step by step, the collectionsArray looks perfectly fine and has data in it.
//Create array based on the collections list
const collectionsArray = Array.from(collectionList);
$.ajax({
method: 'POST',
url: '/Collections/UpdateCollectionSortOrder',
data: collectionsArray,
})
.done(function (msg) {
alert('Sent');
});
However, when I run the application and debug the code, the array is received in the Controller as {string[0]}.
Here is the method which is in the Controller, with my mouse hovered over the parameter:
Do not pay attention to the rest of the code in the controller method. I have not really written anything in there of importance yet. I plan to do that once the data is correctly transferred to the Controller.
I have tried dozens of ideas including what you see in the Controller with the serialize function, just to see if it processes the junk data that is getting passed, but it hasn't made a difference.
I have been Googling the issue & reading other StackOverflow posts. I've tried things like adding/changing contentType, dataType, adding 'traditional: true', using JSON.stringify, putting 'data: { collections: collectionsArray }' in a dozen different formats. I tried processing it as a GET instead of POST, I tried using params.
I am out of ideas. Things that have worked for others are not working for me. What am I doing wrong? I'm sure it's something minor.
UPDATE: Here is the code which explains what the collectionList object is:
//Re-assign SortID's via each row's ID value
var collectionList = document.querySelectorAll(".collection-row");
for (var i = 1; i <= collectionList.length; i++) {
collectionList[i - 1].setAttribute('id', i);
}
What I am doing is getting a list off the screen and then re-assigning the ID value, because the point of this screen is to change the sort order of the list. So I'm using the ID field to update the sort order, and then I plan to pass the new IDs and names to the DB, once I can get the array to pass through.
UPDATE: SOLVED!
I want to post this follow up in case anyone else runs into a similar issue.
Thanks to #freedomn-m for their guidance!
So I took the NodeList object (collectionList) and converted it to a 2-dimensional array, pulling out only the fields I need, and then I passed that array onto the controller. My previous efforts were causing me to push all sorts of junk that was not being understood by the system.
//Create a 2-dimensional array based on the collections list
const collectionArray = [];
for (var i = 0; i < collectionList.length; i++) {
collectionArray.push([collectionList[i].id, collectionList[i].children[1].innerHTML]);
}
$.ajax({
method: 'POST',
url: '/Collections/UpdateCollectionSortOrder',
data: { collections: collectionArray }
})
.done(function (msg) {
alert('Sent');
});
2-d array is coming through to the Controller successfully

LungoJS Json, fill content returned into a list

i am a Java Developer and i need to create a SIMPLE app, as i need this to run into ios & Android i decided to try it using lungoJS, my main problem is that i dont know much JavaScript.. :(
well i have created the prototipe of the app using lungo, but now i need to fill a list with the response (on Json) from my server. I saw in lungos api the function that is used to get a Json request. looks like this:
var url = "http://localhos:8080/myService";
var data = {id: 25, length: 50};
var parseResponse = function(result){
//Do something
};
Lungo.Service.json(url, data, parseResponse, "json");
//Another example
var result = Lungo.Service.json(url, "id=25&len=50", null, "json");
my http request is indexed from 1 to 4 so for each element would be "www.myapp.com/api/1" "www.myapp.com/api/2"
....
my question is, hoy could i get the answer (json) of my request and how do i select items for example if i only want the "name" or "surname"...
thanks, hope some1 could help me :)
I solved my problem long time ago, i will share it:
function some_function(callback) {
var my_number = $$.get('http://app.com/applications/3.json',{ }, function(api) {
obj=api;
template="{{#name}}\
\
{{/name}}";
html=Mustache.render(template,obj);
$$('section#main article#main-article').html(html); //Painting Json obtained on my HTML
}
);
;
callback(my_number);
}
// call the function
some_function(function(num) {
// this anonymous function will run when the
// callback is called
console.log("callback called! " + num);
});
This code uses the obtained Json to Prototype HTML, useful to load images or data from server and not stored on local.
BR, Kike

Trying to pull data from parse and render with underscore.js getting empty frields

Trying to pull data from parse.com and use underscore.js I tried using this to build a table of the data. When I run it with hard coded json it works but when I try running it with pulled data returns an empty table.
Parse.initialize("", "");
var allDeals = Parse.Object.extend("Deal");
var query = new Parse.Query(allDeals);
query.find({
success: function(results){
var deals = JSON.stringify(results);
var template = $("#usageList").html();
$("#target").html(_.template(template,{deals:deals}));
},
error: function(error) {
alert('something was wrong');
}
});
Thanks in advance!
Like #mu said it would be easier to see whats in results..
But I have run into this with Parse before. Taking a guess.. You can try this
$('#target').html(_.template(template, { deals: results.models }));
"results" is a backbone collection and "models" holds the array of objects you are after.
Presumably you're getting a JavaScript object of some sort in results in your success callback. Then you serialize that to a JSON string with:
var deals = JSON.stringify(results);
That leaves you with a string in deals and your template probably doesn't know what to do with a string, it probably wants an object or whatever was in results in the first place. Try skipping the stringification and just feed results straight into the template:
$('#target').html(_.template(template, { deals: results }));

How to get JSON from PHP to JS?

I have really been searching for almost 2 hours and have yet to find a good example on how to pass JSON data from PHP to JS. I have a JSON encoding script in PHP that echoes out a JSON script that looks more or less like this (pseudocode).
{
"1": [
{"id":"2","type":"1","description":"Foo","options:[
{"opt_id":"1","opt_desc":"Bar"},
{"opt_id":"2","opt_desc":"Lorem"}],
{"id":"3","type":"3","description":"Ipsum","options:[
...
"6":
{"id":"14","type":"1","description":"Test","options:[
...
etc
Problem is, how can I get this data with JavaScript? My goal is to make a .js script that generates a poll based on these JSON datas, but I honest to god can't find any examples on how to do this. Guessing it is some something like:
Obj jsonData = new Object();
jsonData = $.getJson('url',data,function()){
enter code here
}
Any links to any good examples or similar would be highly appreciated. And I thought that encoding the data in PHP was the tricky part...
EDIT:
I got this code snippet to work, so I can review my whole JSON data in JS. But now I can't seem to figure out how to get to the inner data. It does print out the stage number (1-6) but I can't figure out how to get the question data, and then again the options data within each question. Do I have to experiment with nested each loops?
$(document).ready(function()
{
$('#show-results').click(function()
{
$.post('JSAAN.php', function(data)
{
var pushedData = jQuery.parseJSON(data);
$.each(pushedData, function(i, serverData)
{
alert(i);
})
})
})
});
The idea here is to get into the question information in the middle level and print out the qusetion description, then based on the question type - loop through the options (if any) to create checkbox/radiobutton-groups before going on to the next question. The first number represents which stage of the multi stage poll I am currently working on. My plan is to divide it into 6 stages by hiding/showing various divs until the last page where the form is submitted through Ajax.
Not sure but I think, you can use
$.getJSON('url', data, function(jsonData) {
// operate on return data (jsonData)
});
now you can access and operate on the PHP json data,
if you're going to use it outside the getJson call you can assign it to a variable
var neededData;
$.getJSON('url', data, function(jsonData) {
neededData = jsonData;
});
Try the jQuery documentation: http://api.jquery.com/jQuery.getJSON/
This example should get you started:
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
This example is based on the JSON structure being;
{
"one": "Singular sensation",
"two": "Beady little eyes",
"three": "Little birds pitch by my doorstep"
}
Do not use echo in PHP. It will print string not JSON.
Use json_encode to pass JSON to javascript.
Use can use each to get the values in JSON at javascript end.
Example
http://www.darian-brown.com/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/
If you are using JQuery there is a really simple solution to your approach as you can see here: http://api.jquery.com/jQuery.getJSON/.
Otherwise I just want you to explain that there is no way to access your JSON directly in JavaScript as you tried in your code above. The main point is, that JavaScript runs on your browser while your PHP script runs on your server. So there must definitely be a communication between them. So you have to request the data from the server over http I would suggest.
HTH

web service call and JSON array manipulation in javascript

I need to call a web service from javascript that returns a JSON array in the following format:
["hello","there","I","am","an","array"]
Unfortunately, the javascript library I'm using (Sencha Touch) to load this data into a widget doesn't accept that format as data input. It will work with something like this however:
[["hello"],["there"],["I"],["am"],["an"],["array"]]
So there are two questions here-- how can I call that web service in javascript and then manipulate the returned array into the format I need? I've been looking at jQuery's getJson() method, not sure if that's the way to go or if there are better ways.
The URL that delivers the JSON array is this right here. Thanks for your help.
Here's a jsFiddle showing both parts of what you asked about. I'm using jQuery for my AJAX call (faked in the jsFiddle) and I'm using Underscore.js for the manipulation:
http://jsfiddle.net/JohnMunsch/E7YTQ/
// Part 1: Get the raw data. Unfortunately, within a jsFiddle I can't go get it from a different domain. So I'm
// simulating the call instead.
var rawDataPromise = $.ajax({
url : "/echo/json/",
data : fakeData,
type : "POST"
});
// var rawDataPromise = $.ajax("http://fastmotorcycleservice.cloudapp.net/FastMotorCycleListService.svc/list/Bruno");
rawDataPromise.done(
function (results) {
// Part 2: Manipulate the data into the form we need.
var manipulatedResults = _.map(results, function (item) { return [ item ]; });
console.log(manipulatedResults);
}
);
// You could also pull that together into a single call $.ajax(...).done(function (results) { ... });
once you have the data in one of your local variables you can manipulate it as you want:
var data = the_function_you_use_to_get_data();
var formatted_array = new Array();
for(i in data){
var d = new Array();
d[0] = i;
formatted_array.push(d);
}
i hope it answered your question

Categories