Howto convert JSON to Array - javascript

This is my first question to StackOverflow. I think answer is not so complicate, but I am very new to Javascript.
I have a JQuery AJAX function that parses this JSON object:
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
and should obtain the same result as:
var sections = [{
key: 1,
label: "Tom Clancy"
}, {
key: 12,
label: "Steve Martin"
}
];
I'm able to iterate through JSON element, but i don't know how to go on.
Can you provide suggestions?
EDIT: i can't still get it work...this is my code:
var sections=[
{key:1, label:"Section A"},
{key:2, label:"Section B"},
{key:3, label:"Section C"},
{key:4, label:"Section D"}
];
$.ajax({
url: '/WebOffice/ListaUtenti',
type: "POST",
dataType: 'json',
success: function (data)
{
console.log( "success" );
sections = data.Users;
}});
scheduler.createTimelineView({
name: "matrix",
x_unit: "day",
x_date: "%d %M",
x_step: 1,
x_size: 15,
y_unit: sections,
y_property: "section_id"
});
The jquery ajax call doesn't assign the new value to sections (the call state is success, verified) and so scheduler still shows the original sections. Where i'm wrong?
thanks

I will explain you the process. Go to any online JSON formatter, may be this one and pretty print your JSON. It will appear as.
{
"Users":[
{
"key":"1",
"label":"Tom Clancy"
},
{
"key":"12",
"label":"Steve Martin"
}
]
}
So Users is an array of objects. Users[0] is first object and Users[1] is second object.
So you can iterate the JSON easily and obtain the result you want.
Live demo : http://jsfiddle.net/sbymr/
See the console for the output.

Related

Server side pagination in KTDatatable (Metronic)

I am new to KTDatatable in Metronic.
I am trying to use server side pagination in Metronic dashboard, and I am parsing the data in a KTDatatable, but I can't find a way to parse the returned data from the API and to view number of pages and each page URL.
The code that I was able to write so far is:
data: {
type: 'remote',
source: {
read: {
url: dataURL,
method: 'GET',
contentType: 'application/json',
map: function(data) {
var cards = data.cards.data;
var currentPage = data.cards.current_page;
var lastPage = data.cards.last_page;
return cards;
}
},
},
pageSize: 10,
serverPaging: true,
},
In this code I was able to get the first ten records but:
1- I wasn't able to parse them the way I want in the table.
2- I wasn't able to show the pages number nor calling the API for the second page or the (x) page I want.
These are the things I want to do.
Thanks in advance.
You can go back to the end of the KT-Datatable documentation to find most of answers you want KT-Datable documentation, but I am gonna explain more hoping it will be more clear.
So the returned value from the API (Json) should look have two main objects meta and data, and it looks something like this:
{
"meta": {
"sort": "desc",
"field": "IssueName",
"page": 1,
"pages": 2,
"perpage": "10",
"total": 11
},
"data": [
{
"IssueName": "******",
"CardNumber": "******"
},
{
"IssueName": "******",
"CardNumber": "******"
}
]
}
And after getting the values of the response from the API you should only return the data object to be parsed by the datatable so the map function should look something like this:
map: function(data) {
return data.data;
}
and it will process the meta data itself.
To parse the data into the columns you should use the same key name of the data in column definition array, so in my example I used it like this:
columns: [
{
field: 'IssueName',
title: columnsTitles.issue,
type: 'string',
},
{
field: 'CardNumber',
title: columnsTitles.card_number,
type: 'string',
},
]
And every time the datatable calls the API it will send more data that will help you give the right response, the data will be on a shape of an array (The field name should be the same as the key):
[
"pagination" => array:4 [
"page" => "1"
"pages" => "2"
"perpage" => "10"
"total" => "11"
],
"sort" => array:2 [
"field" => "IssueName"
"sort" => "desc"
],
]
The sent data is related with the pagination and sorting type you have to get from the API, and you can also add filters and they will be stored in the array in the "query" field, and you can handle them in the backend.

How to split json array from ajax GET into objects?

Good night everyone.
I've seen this question answered in other posts, but no answer works for me, I'm new in ajax/json and I'm a bit lost.
I have this ajax call that returns me a JSON array:
$.ajax({
type: "GET",
url: common.RestURL.index,
dataType: 'json'
}).done(parameters => {
//Fill parameters
drawSettings(parameters);
}).fail(function (jqXHR, textStatus, error) {
showMsg(jqXHR.responseJSON.message,
"Error",
"error");
});
This is the exact json object to return:
"config": [
{
"configDescription": "description1",
"configValue": "value1",
"configKey": "key1",
"idCompany": "company1",
"appConfigurationId": "config1",
"configType": "List"
},
{
"configDescription": "description2",
"configValue": "value2",
"configKey": "key2",
"idCompany": "company2",
"appConfigurationId": "config2",
"configType": "Date"
},
{
"configDescription": "description3",
"configValue": "value3",
"configKey": "key3",
"idCompany": "company3",
"appConfigurationId": "config3",
"configType": "String"
},
{
"configDescription": "description4",
"configValue": "value4",
"configKey": "key4",
"idCompany": "company4",
"appConfigurationId": "config4",
"configType": "Boolean"
}]
So when the ajax call gets the json array, it calls another method that works with each of the objects in the array, but when I try to create each object, they are created empty and I can't find the problem, this is the function I'm talking about:
function drawSettings(parameters) {
if (!$.isArray(parameters)) {
parameters = [parameters];
}
//Fill params in div
$.each(parameters, function (key, value) {
//Parameter to draw
console.log("value .........................." + value.configDescription);
let param = new Parameter(value);
console.log("objetooo ------------ " + param.configDescription);
The Parameter class is a simple class with the attributes of the json ojects and the logs show the attributes with "undefined" value.
Can please someone help me understand and solve the problem?
Thanks to everyone in advance!

my JSON is not practical and I want to change it, how can I do so?

Problem: my JSON isn't practical and I want to change it. As you can see my JSON looks strange, but somehow it's valid JSON (checked with JSONLint). I have input fields which are in containers with their own unique id (they increment). I was wondering if it's possible to send the data inserted into the input fields together so when I fetch it, it will stay together.
how my JSON looks like right now:
{
"main_object": {
"id": "new",
"formData": {
"language": "nl_NL",
"getExerciseTitle": "ExampleForStackOverflow",
"question_takeAudio_exerciseWord[0": "ExampleForStackOverflow",
"Syllablescounter[0": "Example",
"Syllablescounter[1": "Example1",
"question_takeAudio_exerciseWord[1": "SecondExampleForStackOverflow",
"Syllablescounter[2": "Second",
"Syllablescounter[3": "Example"
}
}
}
what I am looking and hoping to achieve:
{ "main_object":
{
"id": "new",
"formData": [
{
"language": "nl_NL",
"getExerciseTitle": "ExampleForStackOverflow",
"Word": "ExampleForStackOverflow",
"Syllables":["Example", "Example1"]
},
{
"Word": "SecondExampleForStackOverflow",
"Syllables": ["Second", "Example"]
}
]
}
};
https://jsfiddle.net/StackOverflowAccount/sa2eowhh/ I have a fiddle so you can see what I mean. When you click on the green + button it adds a whole field. This is a container that has an ID, I am trying to keep everything with the same ID with each other in the JSON file, so when I fetch it to my front-end it "knows" which syllables are part of the exercise word.
I have an ajax call which I think causes my JSON file to look like what I have right now.
my ajax call:
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
formData: JSON.parse('{"' + decodeURI($('#my_form').serialize()).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"') + '"}')
},
dataType: 'json',
}).done(function(response) {
});
});
}
Thanks!

Convert XML Data to Json Format AngularJS

I am trying to use Treeview directive from AngularJS. The stored procedure is returning xml.The tree view directive takes json format. The Controller will get the data from service.I am stuck trying to convert xml to json in service.
Following is the xml structure:
<Company Data="New Company">
<Manager Data="Working">
<Employee Data="ABC" />
<Employee Data="DEF" />
<Employee Data="GHI">
<SubEmployee Data="Approval">
<Stuff Data="Financial" />
<Stuff Data="Consol" />
</SubEmployee>
<SubEmployee Data="Rolled-Over">
<Stuff Data="Corporate" />
</SubEmployee>
</Employee>
</Manager>
</Company>
Below is the expected JSON :
[
{
label: "New Company",
id: "Company",
children: [
{
label: "Working",
id: "Manager",
children: [
{
label: "ABC",
id: "Employee",
children: [
]
},
{
label: "DEF",
id: "Employee",
children: [
]
},
{
label: "GHI",
id: "Employee",
children: [
{
label: "Approval",
id: "SubEmployee",
children: [
{
label: "Financial",
id: "Stuff",
children: [
]
},
{
label: "Consol",
id: "Stuff",
children: [
]
}
]
},
{
label: "RolledOver",
id: "SubEmployee",
children: [
{
label: "Corporate",
id: "Stuff",
children: [
]
}
]
}
]
}
]
}
]
You have two choices:
Return the data from the API in the JSON format you require
Convert the XML to JSON in your angular application using javascript.
I would recommend option 1 if that is possible. For option 2 take a look at this question which disucsses XML/JSON conversion in Javascript
"Convert XML to JSON (and back) using Javascript"
If you read the answers on the above link you will see why option 1 is preferable. Converting between these formats can be problematic.
If you have JQuery available in that page you can convert the XML into a DOM object by doing var data = jQuery(data);. Then, use jQuery selectors to extract the data you need out of it.
Some examples:
// Extract an attribute from a node:
$scope.event.isLive = jQuery(data).find('event').attr('state') === 'Live';
// Extract a node's value:
$scope.event.title = jQuery('title', data).text();
A little late but I am also having to look at this option since I will be working with a CMS that only parses into XML. Which at this stage of the game I have no clue why... but I digress.
Found this on D-Zone and it seems to have potential:
https://dzone.com/articles/convert-xml-to-json-in-angular-js
Basically, you make the request to get the XML, then convert it to JSON within another function. Granted you are still pulling XML data but you will be able to work with JSON which will save you a lot of time.
EX from Site (Requires 3rd party Plugin X2JS)
var app = angular.module('httpApp', []);
app.controller('httpController', function ($scope, $http) {
$http.get("Sitemap.xml",
{
transformResponse: function (cnv) {
var x2js = new X2JS();
var aftCnv = x2js.xml_str2json(cnv);
return aftCnv;
}
})
.success(function (response) {
console.log(response);
});
});
One more note, if you are using Angular like me then someone has already created a nice plugin service to use:
https://github.com/johngeorgewright/angular-xml

Autocomplete in jQuery 1.4.2 jQuery UI 1.8.3

I must be thick because I cannot for the life of me get jQuery autocomplete to work. I have searched for many many examples, and it seems that most of them use an older version of jQuery. I found one fairly good example directly from the jQuery UI site: http://jqueryui.com/demos/autocomplete/#remote-jsonp So I modeled mine after that example. When I type in my input box, the little autocomplete box pops underneath the input box, but there is nothing in the autocomplete box. My data is not being loaded correctly by jQuery.
My datasource is a URL that returns JSON data. Example:
[{
"pk": 1,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "TBA"
}
}, {
"pk": 2,
"model": "concierge.location",
"fields": {
"online": false,
"link": "",
"email": "",
"address": "UB 2008"
}
}]
My Javascript code:
$(document).ready(function() {
$("input#id_location_address").autocomplete({
max: 10,
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
console.log( data )
response( data, function(item) {
return { label: item.address, value: item.address }
});
}
});
}
});
});
So when I console.log(data) in Firebug, it shows the object with all the data in tact. I think I am not accessing the 'address' properly in my Javascript code. See really, I just want the 'address' to pop up in the autocomplete box. How do I do this?
Thanks in advance,
Chris
I figured it out. Needed to loop through the array of json objects and then put the data into an array. I got the idea of returning an array from the defualt jQuery UI example http://jqueryui.com/demos/autocomplete/#default
$('input#id_location_address').keyup( function() {
$("input#id_location_address").autocomplete({
source: function(request, response) {
$.ajax({
url: "/concierge/autocomplete/locations/",
dataType: "json",
data: request,
success: function( data ) {
// loop through data and return as array
items = new Array();
for(item in data) items.push( data[item].fields.address );
response( items );
}
});
}
});
});
Try:
response($.map(data, function(item) {
return {
label: item.fields.address, // item.FIELDS ;)
value: item.fields.address
}
}));
Indeed, response expects an array as argument. $.map iterates over the data items and forms a new array of the return value from the passed mutator method. Once done, $.map returns the new array which will be the argument of response().
try
response($.map(data, function(item) {
return {
label: item.fields.address,
value: item.fields.address
}
}));
see the source of this demo

Categories

Resources