How do I create JSON in ExtJS for an AJAX call? - javascript

I want to create this parameter file so that I can send it to my web service.
var parms = {
"quiz_id":"120",
"owner_id":"1",
"solver_id":"1",
"answers":
[
{
"answer_text" : "YES",
"question_id" : "1"
},
{
"answer_text" : "NO",
"question_id" : "2"
},
{
"answer_text" : "YES",
"question_id" : "3"
},
{
"answer_text" : "YES",
"question_id" : "4"
},
{
"answer_text" : "YES",
"question_id" : "5"
}
]
};
I am stuck with the contents inside of the answers. I don't know how to create it dynamically.

for serializing Javascript objects to JSON strings either you can use
JSON.stringify(Object);
which is available in most of the latest browers, else you can use ExtJS inbuilt method
Ext.encode(Object);
and for deserializing JSON string you can use JSON.parse(JSONString) or Ext.decode(JSONString)

An easy way to do this is to create your data as a javascript object and then use a Json "stringifier" to turn it into a json string, which can then be passed to your server.
This same problem was answered previously at Serializing an object to JSON
If you use jquery (and I highly recommend it as a very useful tool for all serious javascript programmers), there is a nice plugin that I use for passing json back and forth in Ajax calls. See http://code.google.com/p/jquery-json/

Create an object with array and some objects inside and then look at the Ext.data.proxy.Server.encodeFilters() method.

Related

JavaScript convert JavaScript object to JSON object

What is the shortest method to convert a JavaScript object to a JSON object? The beneath is my JavaScript object.
{
"body": [
{
"id": "1",
"action": "alert",
"activityGroupNames": "test2"
},
{
"id": "2",
"action": "alert",
"activityGroupNames": "test3"
},
{
"id": "3",
"action": "alert",
"activityGroupNames": "test2"
}
]
}
I making use of an inline code script in Microsoft automate that performs the following in JavaScript:
var threat = workflowContext.actions.Compose.outputs;
var value = Object.values(threat);
return value;
I am supposed to HTTP POST a JSON object in an API request, however, I am submitting a JavaScript object type and am unsure as to how I can change this. Any help would be greatly appreciated! Please let me know if you require any further context.
Edit: The HTTP POST request is failing due to "Object reference not set to an instance of an object"
Javascript provides with built-in method JSON.stringify() It will help you to convert JavaScript object into JSON and pass through HTTP Request
console.log(JSON.stringify({ x: 5, y: 6 }));
// expected output: "{"x":5,"y":6}"
A common use of JSON is to exchange data to/from a web server.
When receiving data from a web server, the data is always a string.
Parse the data with JSON.parse(), and the data becomes a JavaScript object.
const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);

node.js correct extending of json objects

I'm currently using node-ews in a project to access an Exchange Web Server via node.js. Now i ran into a weird problem. To run for example a "CreateItem" request, which can be an E-Mail or Appointment for example, I'm giving the function the arguments as a json similar to this
var args = {
"attributes" : {
"SendMeetingInvitations" : "SendToAllAndSaveCopy"
},
"SavedItemFolderId": {
"DistinguishedFolderId": {
"attributes": {
"Id": "calendar"
}
}
},
"Items" : {
"CalendarItem" : {
"Subject" : "",
"Body" : {
"attributes" : {
},
"$value" : ""
},
"ReminderIsSet" : "true",
"ReminderMinutesBeforeStart" : "30",
"Start" : "",
"End" : "",
"IsAllDayEvent" : "false",
"LegacyFreeBusyStatus" : "Busy",
"Location" : ""
}
}
};
As the REST-API I'm writing will receive Attributes like Subject, Start, End etc. I initially stripped out those out of the JSON and would define them later like
args.Items.CalendarItem.Subject = req.body.Subject;
Oddly this will make the internal validation of node-ews fail and tell me that CalendarItem has an invalid Child Subject. If i leave Subject als an empty string in the initial args and later change it set it to req.body.Subject it works just fine.
My question is this: Is the Object somewhat different if I later add attributes and if yes is there a way to do it right? Because I don't think its the best way to have a bunch of empty Attributes in my Object if they aren't used and define standard values for all of them even if api won't require them to be sent.
Would great if someone knew the answer. Hope i could clarify what the problem is
Ok,
so the problem seems to be this. Internally the JSON "object" seems to have an order based on the order the variable is defined. in JavaScript this is no problem. But when the xml is parsed, the tag that was defined last will also be at the end of the xml so if you had
<someTag>
<variable2 />
<variable3 />
</someTag>
and you add variable1 to your json by someTag.variable1 = x in the end the xml will look like this after beeing parsed by node-ews
<someTag>
<variable2 />
<variable3 />
<variable1 >x</variable1>
</someTag>
Now unfortunately the exchange web server seems to be picky about the order of the xml tags. so when you build your json be sure to use the direct order. Changing content of the json later will not affect the order.

JSON vs. Object to store settings

For my project I need to store some settings during the session. For this I build up a JSON Object like this:
var oSettingsJSON = new sap.ui.model.json.JSONModel();
oSettingsJSON.setData({
"partially_search": "true",
"case_sensitive": "true",
"aSearchResults" : [],
"indexOfSearchResults": "0",
"searchedText": "",
"showId": "true"
});
So, now I got the idea to store this data in an object, becaus then I needn't to write every time model.getProperty(property) or model.setProperty(property, value).I understand JSON and objects, it's only about a best practiceor something to handle settings. What is more often used in the real world,or doesn't it matter what to use?
JSON stands for Javascript Object Notation. See here. Basically, if you want to store data inside a Javascript Object, then you should use JSON, since it is very simple to comprehend/use and there is virtually no server application technology without a parser for it. Since you are already using Javascript, JSON is recommended.
For instance this is a JSON object:
{
"partially_search": "true",
"case_sensitive": "true",
"aSearchResults" : [],
"indexOfSearchResults": "0",
"searchedText": "",
"showId": "true"
}

Getting fewer/matching objects from json file

My json file looks like this:
[
{
"id" : "1",
"type" : "hardware"
},
{
"id" : "2",
"type" : "software"
}
]
Now when I run following code :
$http({
method: 'get',
url: '/tools.json'
}).success(function(data, status, headers, config) {
///whatever
})
I get these two objects for rederning via ng-repeat, that's fine.
Now, I want to create filters in my app, like display only "Hardware" or "Software", for this, which is the best way to achieve this, is there a way where I can just get Hardware typed objects from JSON itself? (querying JSON and get matching objects) and how can I do that? What should I change in code in-order to do this or should I use Angular filters to render Hardware types after getting entire JSON.
I don't have much experience in Angular, let me know if there is any other way I can achieve what I want.
Thanks in advance.
It's your choice completely.
Ideally, your backend should be returning the JSON filtered by the query.
If you want instant-responsiveness, you may use Angularjs's filters to do the filtering for you on the same data which you'd fetch once from the server. This also has an added benefit of doing full-text search, which is really neat.
If you just want to filter the JSON data, you could use the reduce method as follows:
var hardware = data.reduce(function(result, current) {
if(current.type === 'hardware') {
result.push(current);
}
return result;
}, []);
Fiddle available here.
The ideal place for this filtering would be on backend, given the type. But for some reason, if you want to do this on browser, you can use a simple for loop to filter objects with type hardware. A cleaner way of doing this would be with underscore. Include underscore source file in your project and do _.filter function to filter the objects you want. You can read more about filter function here: http://underscorejs.org/#filter

How to load a single JSON file into a SproutCore model?

I have a single JSON file whose structure is not uniform to load into a single model. It has the data for a screen. The typical JSON structure is like below.
{
"Model1":{
"key1":"value1",
"key2" : "value2"
},
"Model2":[
{
"key1":"value1",
"key2" : "value2"
},
{
"key1":"value1",
"key2" : "value2"
"subModel":[
{
"key1":"value1",
"key2" : "value2"
},
{
"key1":"value1",
"key2" : "value2"
}
]
}
]
Now I have to divide this JSON and load it into different models. From the server I will get only one JSON. How can I achieve it in SproutCore?
Research that I have done:
I have searched in Google with the phrase "How to load single JSON into SproutCore model?". However, I didn't get any results which answer my question. I have also searched on Stack Overflow. But I didn't get any results here either. Hence I didn't get any approach/ideas/inputs/approaches to try with, I don't have any code sample to show what I have tried.
Assumptions:
Your json is string.
You have an SC.Store
Your models are defined as SC.Record instances (e.g. App.Model1)
then you can do
var json = JSON.parse(yourJsonString);
var model1 = json["Model1"];
var model2Arr = json['Model2'];
// loadRecord for a single instance
store.loadRecord(App.Model1, model1, model1.serverIdProp);
// loadRecords for a bunch of instances
store.loadRecords(App.Model2, model2Arr, model2Arr.getEach('serverIdProp'));
Note: your json should have some sort of id that the server assigns to your model instances.

Categories