How to create JSON object using jQuery - json

I have a JSON object in below format:
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],
How can i create JSON object in jquery for above format. I want to create a dynamic JSON object.

Just put your data into an Object like this:
var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
myObject.pets = ["cat", "dog"];
Afterwards stringify it via:
var myString = JSON.stringify(myObject);
You don't need jQuery for this. It's pure JS.

A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.
If you want to convert your javascript object to a json string, use JSON.stringify(yourObject);
If you want to create a javascript object, simply do it like this :
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};

I believe he is asking to write the new json to a directory. You will need some Javascript and PHP. So, to piggy back off the other answers:
script.js
var yourObject = {
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
};
var myString = 'newData='+JSON.stringify(yourObject); //converts json to string and prepends the POST variable name
$.ajax({
type: "POST",
url: "buildJson.php", //the name and location of your php file
data: myString, //add the converted json string to a document.
success: function() {alert('sucess');} //just to make sure it got to this point.
});
return false; //prevents the page from reloading. this helps if you want to bind this whole process to a click event.
buildJson.php
<?php
$file = "data.json"; //name and location of json file. if the file doesn't exist, it will be created with this name
$fh = fopen($file, 'a'); //'a' will append the data to the end of the file. there are other arguemnts for fopen that might help you a little more. google 'fopen php'.
$new_data = $_POST["newData"]; //put POST data from ajax request in a variable
fwrite($fh, $new_data); //write the data with fwrite
fclose($fh); //close the dile
?>

How to get append input field value as json like
temp:[
{
test:'test 1',
testData: [
{testName: 'do',testId:''}
],
testRcd:'value'
},
{
test:'test 2',
testData: [
{testName: 'do1',testId:''}
],
testRcd:'value'
}
],

Nested JSON object
var data = {
view:{
type: 'success', note:'Updated successfully',
},
};
You can parse this data.view.type and data.view.note
JSON Object and inside Array
var data = {
view: [
{type: 'success', note:'updated successfully'}
],
};
You can parse this data.view[0].type and data.view[0].note

var model = {"Id": "xx", "Name":"Ravi"};
$.ajax({ url: 'test/set',
type: "POST",
data: model,
success: function (res) {
if (res != null) {
alert("done.");
}
},
error: function (res) {
}
});

Related

Format HERE Map API JSON Response

I am experiencing an issue formatting the JSON response from the HERE Map API for an isoline. The full HERE API JSON response is shown below and contains Lat/Long coordinates for a line as shown below.
{
"response": {
"metaInfo": {
"timestamp": "2017-03-03T23:40:34Z",
"mapVersion": "8.30.68.151",
"moduleVersion": "7.2.201709-111134",
"interfaceVersion": "2.6.29"
},
"center": {
"latitude": 34.603565,
"longitude": -98.3959
},
"isoline": [
{
"range": 300,
"component": [
{
"id": 0,
"shape": [
"34.6096802,-98.4147549",
"34.6096802,-98.4141541",
"34.6098518,-98.4136391",
"34.6101952,-98.4132957",
"34.6103668,-98.4127808",
"34.6101952,-98.4122658",
"34.6098518,-98.4119225",
"34.6098518,-98.4115791",
"34.6101952,-98.4112358",
"34.5998955,-98.4115791",
"34.6002388,-98.4126091",
"34.6005821,-98.4129524",
"34.6009254,-98.4139824",
"34.6019554,-98.4143257",
"34.6022987,-98.4153557",
....
"34.6081352,-98.4129524",
"34.6083069,-98.4134674",
"34.6083069,-98.4148407",
"34.6084785,-98.4153557",
"34.6089935,-98.4155273",
"34.6095085,-98.4154415",
"34.6096802,-98.415184",
"34.6096802,-98.4147549"
]
}
]
}
],
"start": {
"linkId": "+888249498",
"mappedPosition": {
"latitude": 34.6034836,
"longitude": -98.3959009
},
"originalPosition": {
"latitude": 34.603565,
"longitude": -98.3959
}
}
}
}
I am mapping the isoline data in Leaflet as a polygon. I can do it manually like this, and all works well.
var polygon = L.polygon([
[34.6343994, -98.7664032],
[34.6357727, -98.76297],
[34.6385193, -98.7602234],
[34.6398926, -98.7561035],
[34.6385193, -98.7519836],
[34.6357727, -98.7492371],
[34.6357727, -98.7464905],
.....
[34.6302795, -98.7712097],
[34.6330261, -98.7718964],
[34.6343994, -98.7698364],
[34.6343994, -98.7664032]
]
).addTo(map);
Am now trying to automate it but cannot get the json output into a compatible format for Leaflet. I can make the API call, capture the JSON response, and extract the array of lat/long coordinates using the following code:
function getJson(url) {
return JSON.parse($.ajax({
type: 'GET',
data: '',
url: url,
dataType: 'json',
global: false,
async: false,
success: function (data) {
return data;
}
}).responseText);
}
var myJsonObj = getJson('https://isoline.route.cit.api.here.com/routing/7.2/calculateisoline.json?mode=fastest;car;traffic:disabled&jsonAttributes=1&rangetype=time&start=34.603565,-98.3959&app_id=id&app_code=codeg&range=1800');
var isoline = myJsonObj.response.isoline[0].component[0].shape;
The variable isoline looks like this (an array of lat/long coordinate pairs) but I cannot get them into an array of arrays as needed for Leaflet.
[
"34.6096802,-98.4147549",
"34.6096802,-98.4141541",
"34.6098518,-98.4136391",
"34.6101952,-98.4132957",
"34.6103668,-98.4127808",
"34.6101952,-98.4122658",
"34.6098518,-98.4119225",
"34.6098518,-98.4115791",
"34.6101952,-98.4112358",
"34.5998955,-98.4115791",
"34.6002388,-98.4126091",
"34.6005821,-98.4129524",
"34.6009254,-98.4139824",
"34.6019554,-98.4143257",
"34.6022987,-98.4153557",
....
"34.6081352,-98.4129524",
"34.6083069,-98.4134674",
"34.6083069,-98.4148407",
"34.6084785,-98.4153557",
"34.6089935,-98.4155273",
"34.6095085,-98.4154415",
"34.6096802,-98.415184",
"34.6096802,-98.4147549"
]
Would appreciate any help in reformatting the coordinates to look like this
[
[34.6343994, -98.7664032],
[34.6357727, -98.76297],
[34.6385193, -98.7602234],
[34.6398926, -98.7561035],
[34.6385193, -98.7519836],
[34.6357727, -98.7492371],
[34.6357727, -98.7464905],
.....
[34.6302795, -98.7712097],
[34.6330261, -98.7718964],
[34.6343994, -98.7698364],
[34.6343994, -98.7664032]
]
It may be that there is a better way of putting the data in Leaflet as well, but Polygon and Polyline are the only methods I can find and they require the coordinates in an array of arrays.
You need to iterate over each element and split, forming an array.
Like this, (ES6 way)
const newArray = array.map(a => a.split(',').map(Number));
or (Non ES6 way)
var newArray = [];
array.forEach(function (a){ newArray.push(a.split(',').map(Number)); });
So your final code should look like this,
function getJson(url) {
return JSON.parse($.ajax({
type: 'GET',
data: '',
url: url,
dataType: 'json',
global: false,
async: false,
success: function (data) {
return data;
}
}).responseText);
}
function parseJSONForPolygon(rawJsonArray) {
var newArray = [];
rawJsonArray.forEach(function (a) { newArray.push(a.split(',').map(Number)); });
return newArray;
};
var myJsonObj = getJson('https://isoline.route.cit.api.here.com/routing/7.2/calculateisoline.json?mode=fastest;car;traffic:disabled&jsonAttributes=1&rangetype=time&start=34.603565,-98.3959&app_id=id&app_code=codeg&range=1800');
var isoline = parseJSONForPolygon(myJsonObj.response.isoline[0].component[0].shape);
.map(Number) credit goes to
https://stackoverflow.com/a/15677905/923426
let polygonArray = [];
data.response.isoline.component.shape.forEach((elm) => {
polygonArray.push(elm.split(','));
})
now your polygonArray will be acceptable by leaflet

How to convert Backbone fetched object to proper Handlebars JSON Object?

Currently I have an issue with getting back a proper JSON object I'm fetching with Backbone fetch() and putting it into a Handlebars template.
See below my code, I have made a ugly workaround for now to test my Backend API
When converting to JSON with *.toJSON(), it just adds an extra object in-between and I don't need this extra object
Object [0]
--> books
----> Object [0]
------> Array of book
--------> book
--------> cities
JSON
{
"books": [
{
"book": 00001,
"cities": [
"TEST"
]
},
{
"book": 00002,
"cities": [
"TEST"
]
},
{
"book": 00003,
"cities": [
"TEST"
]
}
],
"more": true
}
JavaScript
var Book = Backbone.Model.extend({
default: {
book: 0,
cities: ["TEST1", "TEST2", "TEST3"]
},
url: function () {
return ".list.json";
}
});
var Books = Backbone.Collection.extend({
model: Book,
url: ".list.json"
});
var BooksView = Backbone.View.extend({
initialize: function(){
_.bindAll(this, 'render');
this.collection = new Books();
this.collection.fetch();
this.source = $('.e-books-template').html();
// Use an extern template
this.template = Handlebars.compile(this.source);
var self = this;
this.collection.fetch({
success: function () {
self.render();
},
error: function () {
console.log("ERROR IN BooksView");
}
});
},
render: function() {
var collect = JSON.stringify(this.collection);
collect = collect.slice(1, -1);
var html = this.template($.parseJSON(collect));
this.$el.html(html);
}
});
var booksView = new BooksView({ });
$(document).ready(function(){
booksView.$el = $('.e-books-content');
});
A Backbone collection expects an array of models but your JSON provides an object with the array under a books key. Parse the server response to format the data :
var Books = Backbone.Collection.extend({
model: Book,
url: ".list.json",
parse: function(data) {
return data.books;
}
});
Pass your data to your template via http://backbonejs.org/#Collection-toJSON ,
// directly as an array in your template
var html = this.template(this.collection.toJSON());
// under a books key
var html = this.template({
books: this.collection.toJSON()
});
And a demo http://jsfiddle.net/nikoshr/8jdb13jg/

Dojo ItemFileWriteStore not reading JSON server file

I am using Dojo and it's dojo/data/ItemFileWriteStore module to read a JSON data file on my local server. In my .js file I have
var myDataStore = new ItemFileWriteStore({
url: "app/data/mydata.json",
handleAs: "json",
clearOnClose: true,
urlPreventCache: true
})
This is located in the postCreate function for my return declare function... so:
define([
"dojo/_base/declare",
"com/cayuse/base/_widget",
"dojo/text!./templates/myform.html",
...
"dojo/data/ItemFileWriteStore",
"dojo/store/DataStore",
"dojo/store/Observable",
"dojo/data/ObjectStore",
"dojo/domReady!"
],
function(declare, widget, template, ..., ItemFileWriteStore, DataStore,
Observable, ObjectStore){
return declare("app.myform", widget, {
templateString: template,
postCreate: function(){
domConstruct.create("link",{
type: "text/css",
rel: "stylesheet",
href: require.toUrl('dojox/form/resources/CheckedMultiSelect.css')
}, document.getElementsByTagName("head")[0]);
// data store
var myDataStore = new ItemFileWriteStore({
url: "app/data/mydata.json",
handleAs: "json",
clearOnClose: true,
urlPreventCache: true
})
console.log(myDataStore);
}
});
}
);
I can change the data store access from what you see above using IFWS method to
var myDataStore = dojo.xhrGet({
url: "app/data/mydata.json",
handleAs: "json",
load: function(data, ioArgs){
console.log(data);
}
});
and it finds the file with no problems.
This is so bizarre! Any ideas on what is going wrong here?
UPDATED:
Here is the data in the file I am reading. I believe it conforms to the JSON format. Let me know if not. xhrGet reads it fine.
{ "identifier": "id",
"label": "firstName",
"items":[
{"id":"0","firstName":"Robert","website":"www.barker.com","email":"robert#barker.com","bday":"1928-08-09","color":"Blue","toolkits":["Dojo","Moo"],"sendEmail":["on"],"format":"HTML"},
{"id":"1","firstName":"Vanna","website":"www.white.com","email":"vanna#white.com","bday":"1968-07-23","color":"Green","toolkits":["Dojo","jQuery"],"sendEmail":["off"],"format":"Text"}
]
}
ItemFileWriteStore requires your data being structured into something like this:
{ identifier: 'abbr',
label: 'name',
items: [
{ abbr:'ec', name:'Ecuador', capital:'Quito' },
{ abbr:'eg', name:'Egypt', capital:'Cairo' },
{ abbr:'sv', name:'El Salvador', capital:'San Salvador' },
{ abbr:'gq', name:'Equatorial Guinea', capital:'Malabo' },
{ abbr:'er', name:'Eritrea', capital:'Asmara' },
{ abbr:'ee', name:'Estonia', capital:'Tallinn' },
{ abbr:'et', name:'Ethiopia', capital:'Addis Ababa' }
]}
That is 'identifier' being your "ID" field, 'label' being your "label" field and then all your objects inside an array called "items".
You can check it out here in ItemFileWriteStore's documentation. If you don't have your JSON data structured like that it's possible that you may end up reading your file with the IFWS and actually not reading any data.
There are other store implementations in dojo 1.7 that don't require such structure, e.g. Memory Store that you can combine with other file reading techniques to achieve the same.
Try using dojo.data.ItemFileReadStore for reading
json data files, instead of dojo/data/ItemFileWriteStore.
Note that dojo.data.ItemFileWriteStore is used for writting json data.
If your code is EXACTLY as you posted it above then the interpreter might not like the fact that you omitted the semicolon from the ItemFileWriteStore assignment. Try adding the ';' as below:
// data store
var myDataStore = new ItemFileWriteStore({
url: "app/data/mydata.json",
handleAs: "json",
clearOnClose: true,
urlPreventCache: true
});
console.log(myDataStore);

jqgrid - can I access server response with onSelectRow?

I get a JSON response from the server that I have full access to using loadComplete. Is it possible to be able to access the JSON response using
onSelectRow?
any other custom function defined outside of loadComplete?
You can define a variable which will hold the last state of the JSON response returned from the server:
var serverData;
$('#list').jqGrid({
datatype: 'json',
// ... other parameters
loadComplete: function (data) {
serverData = data; // or serverData = data.rows
// ...
},
onSelectRow: function (id) {
if (serverData) {
// here you can access serverData, but you need
// here probably find the item in the serverData
// which corresponds the id
}
}
});
If you have JSON data for example from the form
{
"total": "xxx",
"page": "yyy",
"records": "zzz",
"rows" : [
{"id" :"1", "cell": ["cell11", "cell12", "cell13"]},
{"id" :"2", "cell": ["cell21", "cell22", "cell23"]},
...
]
}
then you can save in serverData not the data directly. It could be interesting to save only cell part and save it as the value of the serverData[id]:
var serverData = [];
$('#list').jqGrid({
datatype: 'json',
// ... other parameters
loadComplete: function (data) {
var i, rows = data.rows, l = rows.length, item;
for (i = 0; i < l; i++) {
item = rows[i];
serverData[item.id] = item.cell;
}
// ...
},
onSelectRow: function (id) {
var item = serverData[id]; // the part of data which we need
}
});
If you use repeatitems: false setting in the jsonReader then you can save in the serverData only the part of the items (selected properties) which represented the row of the server data.
In any way you should save the part of the information from data parameter of loadComplete in some variable defined outside of the loadComplete.

How do I get an ExtJS JsonStore to put the JSON data directly into the request body?

I have a JsonStore configured like so:
var store = new Ext.data.JsonStore({
restful: true,
url: '/categories',
remoteSort: true,
idProperty: 'Id',
totalProperty: 'total',
root: 'results',
writer: new Ext.data.JsonWriter({
encode: false
}),
fields: [ 'Id', 'Name' ]
});
I grab some data from the server, then edit one of the records. When I tell the store to save, it sends this JSON back to the server:
{
"results":
{
"Name":"Trivial123",
"Id":2
}
}
The store is wrapping the JSON inside the results property (the root property configured on the store). However, the server expects this:
{
"Name":"Trivial123",
"Id":2
}
In other words, the serialized entity should be put directly in the response body, and not wrapped in a property. Does anyone know how I can configure the store to do this?
You need to override the data rendering function in the JsonWriter, like so:
var rootlessRenderFunction = function (params, baseParams, data) {
if (this.encode === true) {
Ext.apply(params, baseParams);
params = Ext.encode(data);
} else {
params.jsonData = data;
}
};
var myWriter = new Ext.data.JsonWriter({
encode: false,
writeAllFields: true
});
myWriter.render = rootlessRenderFunction;
var myStore = new Ext.data.JsonStore({
// ... various config values ...
writer: myWriter
});
This "rootlessRenderFunction" implementation is the same as the Ext JsonWriter's render code except it doesn't interpose a root in the request data.
This is a hack, of course.
I'm assuming you can't just not set the root value for the store for some reason? That's the way I normally do it.