dsDetails = new kendo.data.DataSource({
transport: {
read: {
url: PRODUCTDETAILAPI,
dataType: "json",
data: { "site_key": SITEKEY, "id": id }
}
}
});
dsDetails.fetch(function() {
var myData = dsDetails.data();
console.log(myData);
// bind stuff here
});
The API call is returning the following data (so I know that is working):
{
"main_category": "Gifts",
"expires_on": null,
"html_address": "678 Sterling Drive\u003Cbr/\u003ESuite 102\u003Cbr/\u003ESanford FL 32771",
"address": "678 Sterling Drive Suite 102, Sanford Florida 32771",
"status": "Visible",
"rating": 5, "sub_category": "Gift Baskets",
"quantity": 92, "categories": ["Gifts: Gift Baskets"], "title": "Luggage Duffel",
"price": 12210, "images": [], "short_address": "Sanford FL",
"short_title": "Luggage Duffel",
"posted_at": "2011/09/23",
"category": "Gifts: Gift Baskets",
"id": "product_listing_88",
"price_note": "",
"description": "Black, 60 in long",
"seller": "Morning Star Media Group"
}
When I run this code I get the following error:
Uncaught TypeError: Object #<Object> has no method 'slice'
Edit: Based on the selected answer, I replace this kendo dataset code with a standard jQuery .ajax call and it worked fine. My brain was temporarily stuck within the confines of the Kendo framework.
The dataSource is used to get collection of objects from the server. This exception is thrown when the item returned from the server is not the collection. Instead it is an object which has a field that actually holds the array.
If the dataset (array) that you want to use is one of the fields in the returned object, you should use dataSource.schema.data configuration to specify that field, so the dataSource can understand in which field from the response to search the collection.
Related
I am making a db query upon hitting a POST API endpoint. The query needs to update the Json column in my networks table, which only has 3 columns (id, name, and json). I need to specifically update the coreEssentials array with another value, so I have been using the set 'json' = ? SQL query where I paste in the entire column with my changes in the specific field and it works (manually in the db). The only issues are, I need to do make a SQL call to SELECT the json column for a specific id first, (long story, but a backend application generates some data into the JSON (the coreEssentials key/object I need to update) then puts it into the data, then after I need to update).
I was doing this manually in my Postgresql GUI (DBbeaver) and my query simply looks like this:
update network set "json" = '{
"uid": "randomUid",
"etag": "randomEtag",
"name": "randomNameAgain",
"state": "PENDING",
"Type": "ABC",
"version": 1,
"dealerId": "random_uuid",
"Param": {
"AreaId": 0,
"AreaIdStr": "0.0.0.0",
"DeadInterval": 0,
"HelloInterval": 0
},
"networkData": {
"tic": "311",
"toe": "980",
"tac": "201",
"tac_id": "201",
"timeZone": null
},
"production": false,
"customerName": "random_name",
"IPPool": "0.0.0.0/32",
"customerEmail": "random#email.com",
"coreEssentials": [ ],
"deployment": "A"
}'
coreEssentials starts out as an Empty array but I need to set it to this:
[{
"version": 1,
"component": "purple",
"instanceId": "1"
},
{
"version": 1,
"component": "gray",
"instanceId": "1"
},
{
"version": 1,
"component": "blue",
"instanceId": "1"
} ]
I'm using a Node JS backend with pg-promise (Postgresql) library. Can anyone give me advice how to do this query?
I just set coreEssentials array to the data object returned from the first SQL query like #vitaly-t suggested :D
I am new to JQuery. I am trying to develop a small travel website for checking PNR. I am currently using an API provided by one of the travel company. As soon as we hit the API Url, browser displays the result in JSON format.
I am using JQuery, JS and HTML. I want to know how to store the JSON value (in string format) retrieved from hitting an API, in a variable and use it later in the script.
PS: Though I have found many answer in Stackoverflow but none of the result works. Kindly help with the appropriate value.
Sample Code: (I am using one textbox and button)
<script>
function search_pnr(){
var pnr = $('#input_pnr').val();
var result;
var url = "http://api website/pnr"+pnr;
//Suggest the code here, to fetch the result from url and store in the variable result.
</script>
<input type="text" placeholder="Enter PNR" id ="input_pnr"/>
<input type="button" value="Search PNR" onclick="search_pnr()"/>
Below is the JSON value getting from server
{"to_station": {"lng": 77.2888291, "name": "ANAND VIHAR TERMINAL", "lat": 28.6118176, "code": "ANVT"}, "total_passengers": 1, "pnr": "6717552286", "journey_class": {"name": null, "code": "3A"}, "train": {"classes": [{"available": "N", "name": "SECOND AC", "code": "2A"}, {"available": "Y", "name": "THIRD AC", "code": "3A"}, {"available": "N", "name": "SECOND SEATING", "code": "2S"}, {"available": "N", "name": "FIRST AC", "code": "1A"}, {"available": "Y", "name": "AC CHAIR CAR", "code": "CC"}, {"available": "N", "name": "FIRST CLASS", "code": "FC"}, {"available": "N", "name": "3rd AC ECONOMY", "code": "3E"}, {"available": "N", "name": "SLEEPER CLASS", "code": "SL"}], "days": [{"code": "MON", "runs": "N"}, {"code": "TUE", "runs": "Y"}, {"code": "WED", "runs": "N"}, {"code": "THU", "runs": "Y"}, {"code": "FRI", "runs": "N"}, {"code": "SAT", "runs": "Y"}, {"code": "SUN", "runs": "N"}], "number": "22405", "name": "BGP-ANVT GARIB RATH"}, "from_station": {"lng": 86.9828131, "name": "BHAGALPUR", "lat": 25.2494829, "code": "BGP"}, "passengers": [{"booking_status": "CNF/G12/36/GN", "no": 1, "current_status": "CNF/-/0/GN"}], "reservation_upto": {"lng": 77.2888291, "name": "ANAND VIHAR TERMINAL", "lat": 28.6118176, "code": "ANVT"}, "response_code": 200, "boarding_point": {"lng": 86.9828131, "name": "BHAGALPUR", "lat": 25.2494829, "code": "BGP"}, "debit": 3, "doj": "25-08-2018", "chart_prepared": false}
Kindly also help how to read both the objects and array in the given JSON.
You can use ajax to fetch the result from the url
var result;
var url = "http://api website/pnr"+pnr;
$.ajax
({
url: url,
type: 'GET',
dataType: 'json',
success: function(data)
{
result = data;
alert(JSON.stringify(data));
}
});
You just need to parse JSON and how to read each object. This should give you good start
$.ajax({
type: "GET",
url: "http://api_website/pnr"+pnr,
data: data,
success: function(resultData) {
console.log(resultData);
var to_station = resultData.to_station;
var trains = resultData.train;
var passengers = resultData.passengers;
alert("Station Name: "to_station.name);
alert("Passengers: "passengers.booking_status);
},
error(function() {
alert("Something went wrong");
}
});
You can read more bout how to read JSON here.
$.ajax({
method: "GET",
url: url
})
.done(function( data ) {
console.log(data)
// see what properties you need from data object and save it to variable
var data = data
});
First thing,
Use a javascript file....API calls are better off done in a js file rather than in a script tag.
Second thing, if you want to store it in a json format,
you can store it in a value like the way you have declared your url variable.
Since, you are fetching the data, I'm assuming this is a get request, you can find more information about them in the following links -
https://www.sitepoint.com/ajaxjquery-getjson-simple-example/
https://api.jquery.com/jquery.get
Also, if the data isn't very sensitive, you can store it in the local storage of your browser, so that you can access it later on in other web pages as well.
In your current json data, I would say that if you declare it to a variable say
apiResult
Your to_station would be apiResult.to_station, the lng value would be apiResult.to_station.lng and so on.
Hope any of this helps, and good luck.
Everyone already added the AJAX examples, so I will leave that out.
So for reading the objects, you just have to parse what you need through various means, if you know what the object looks like and exactly what you need you can use dot notation. If you are looking to grab things more dynamically you can using higher order functions or for loops as well as Object prototypes example getting the entries (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)
You might consider using localStorage for storing the information depending on what you are using it for which is a built-in Web API
here is MDN's definition
The read-only localStorage property allows you to access a Storage
object for the Document's origin; the stored data is saved across
browser sessions. localStorage is similar to sessionStorage, except
that while data stored in localStorage has no expiration time, data
stored in sessionStorage gets cleared when the page session ends —
that is, when the page is closed.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
You may want to use AJAX. You have to be sure how the server will retrieve the data. If it is in a JSON format do:
<script>
function search_pnr(){
var pnr = $('#input_pnr').val();
var result;
var url = "http://api website/pnr"+pnr;
$.getJSON( url, function( data ) {
result = data;
$.each( data, function( key, value ) {
// whatever with keys and values if needed
}
);
}
</script>
Ref w3 Schools
JQuery official website
All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:
var j={"name":"binchen"};
JSON.stringify(j); // '{"name":"binchen"}'
For more info kindly visit link
Previously I was using a json file with the following format:
[{"lat":43.788458853157117,"lng":-79.282781549043008,"category":"volunteer","name":"Rita","url":"", "description":"xxx is a member of 13"},{"lat":43.7,"lng":-79.4,"category":"organization","name":"TCAN","url":"http://tcan.ca","description":"Lorem ipsum"}]
Now I am attempting to generate the json file from a Drupal site and am getting the following structure. How can I reference the lowest level fields. I have looked at examples using d3.net but have not found any that apply.
{
"organizations": [
{
"member": {
"field_category": "organization",
"body": "A network of organizations in Toronto devoted to climate change mitigation and adaptation.",
"URL": "xxx.ca",
"title": "Toronto Climate Action Network",
"field_lat": 43.7,
"field_long": -79.4
}
},
{
"member": {
"field_category": "abc",
"body": "xxx.",
"URL": "",
"title": "yyy",
"field_lat": 43.7,
"field_long": -79.28
}
}
]
}
Assuming that your data is stored in the variable data:
var bottom = data.organizations.map(function(d) { return d.member; });
I'm binding a JS KendoUI dropdownlist to JSON (not using a model) which recently has been changed by adding a named array to the object (in efforts to format the JSON for a Kendo TreeView control). This broke a few things of course. The original JSON format looked like this (an array of objects):
[
{
"COLUMN_NAME": "OBJECTID",
"DATA_TYPE": "esriFieldTypeOID",
"CATEGORY": "Feature Data"
},
{
"COLUMN_NAME": "Brand",
"DATA_TYPE": "esriFieldTypeString",
"CATEGORY": "Feature Data"
},...
]
now it looks like this (an object with a named array, with objects):
{
"Hydrant": [
{
"COLUMN_NAME": "OBJECTID",
"DATA_TYPE": "esriFieldTypeOID",
"CATEGORY": "Feature Data"
},
{
"COLUMN_NAME": "Brand",
"DATA_TYPE": "esriFieldTypeString",
"CATEGORY": "Feature Data"
},...
],
"DisplayField": "Description",
"DefaultField" : "HydrantID"
}
I assumed I could simply define the schema to "Hydrant" or set the dataText/ValueFields to "Hydrant.COLUMN_NAME" but no luck. What am I overlooking? I am binding this JSON format response to a dropdownlist using the "COLUMN_NAME" to populate it.
bonus: how could I use the "DefaultField" to set the default selection in the dropdownlist?
Thanks in advance!
You can use the schema.data field of the DataSource configuration to identify the field from the response to use for its data:
schema: { data: 'Hydrant' }
I have a json object that I'm loading from wordpress using the JSON API plugin. When I load the json object and try to log out the parts of it, it seems like it treats every single character as its own object so the loop returns me a couple thousand objects all with item in it which is a single character. This is my first time using json so idk if i'm missing a step here. this is the code I'm using so far.
function getProjInfo(theId){
$.ajax({// calling the ajax object of jquery
type: "GET",// we are going to be getting info from this data source
url: 'http://testing.charter21.com/api/get_post/?post_id='+ theId,//the datasource
dataType: "application/json",
success: function(data){
parseJson(data);
}, // what happens when it is successful at loading the XML
error: function(){
alert("error");
}
});
}//end of the function
function parseJson(inData){
postInfo = inData;
$.each(postInfo, function(index, value){
console.log(this);
});
}
the json looks like this:
{
"status": "ok",
"count": 10,
"count_total": 19,
"pages": 2,
"posts": [
{
"id": 175,
"type": "post",
"slug": "home-page-slider",
"url": "http:\/\/testing.charter21.com\/uncategorized\/home-page-slider\/",
"status": "publish",
"title": "Home Page slider",
"title_plain": "Home Page slider",
"content": "<p>The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.<\/p>\n",
"excerpt": "The cImages in here are the images that are in the slider on the home page this content in this box will not show up. Its only here as a guide.",
"date": "2011-01-25 10:40:25",
"modified": "2011-01-25 10:40:25",
"categories": [],
"tags": [],
"author": {
"id": 1,
"slug": "admin",
"name": "admin",
"first_name": "",
"last_name": "",
"nickname": "admin",
"url": "",
"description": ""
},
"comments": [],
"attachments": [],
"comment_count": 0,
"comment_status": "open"
}
so basically instead of giving me "status" as an key and "ok" as a value, i get "s" as an object with an index 0 that has a value of "s" for every single character in the json object. Any help on this matter would be appreciated.
You need to set dataType:json in your $.ajax() request so that jQuery converts the JSON-formatted string into a JavaScript object for you to process as such. You're currently using application/json which is a mime type, and not a valid value for this field in a jQuery request.
In your case you can even try data = eval(data) , this javascript statement should convert your string to json object.
Use the Jquery function:
data = $.parseJSON(data);
before using $.each.
The way I solved it in my AngularJS app is by sending the response from the server (I'm using Node Express) as a JavaScript object, rather than as a string. Nothing else worked for me.
var response = {};
response.error = "Error message";
res.send(response);