This question already has an answer here:
how to build json array dynamically in javascript
(1 answer)
Closed 6 years ago.
I receive a json object with some number of quick reply elements from wit.ai, like this:
"msg": "So glad to have you back. What do you want me to do?
"action_id": "6fd7f2bd-db67-46d2-8742-ec160d9261c1",
"confidence": 0.08098269709064443,
"quickreplies": [
"News?",
"Subscribe?",
"Contribute?",
"Organize?"
],
"type": "msg"
I then need to convert them to a slightly different format as they are passed to FaceBook Messenger as described in the code below. Wit only exposes 'msg' and 'quickreplies.' Can you suggest a good way to do this? It goes after "console.log(element)" as far as I understand.
if (quickreplies){
// got simple array of quickreplies
// need to format quickreplies for FB:
// "quick_replies":[
// {
// "content_type":"text",
// "title":"Red",
// "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_RED"
// },
// {
// "content_type":"text",
// "title":"Green",
// "payload":"DEVELOPER_DEFINED_PAYLOAD_FOR_PICKING_GREEN"
// }]
console.log('we got quickreplies, here they are:');
var quick_replies = []; // ??
quickreplies.forEach(function(element) {
console.log(element)
});
}
else (console.log('no quickreplies'));
In the above example, the end result should be this:
// "quick_replies":[
// {
// "content_type":"text",
// "title":"News",
// "payload":"News"
// },
// {
// "content_type":"text",
// "title":"Subscribe?",
// "payload":"Subscribe?"
// }
// "content_type":"text",
// "title":"Contribute?",
// "payload":"Contribute?"
// },
// {
// "content_type":"text",
// "title":"Organize?",
// "payload":"Organize?"
// }
// ]
Most straightforward way, I think, would be to convert the JSON into an object using JSON.parse().
Then manipulate the object, removing and adding elements as needed.
Once done, using JSON.stringify to convert the object back into a JSON string.
Maybe this can help you out.
function makeReply(text) {
return { content_type: 'text', title: text, payload: text };
}
var replies = { quick_replies: [] };
quickreplies.forEach(function(element) {
replies.quick_replies.push(makeReply(element); // not sure what needs to be supplied for "title" and "payload"
});
Related
I would like to read groups_id_ss for specific id.
How to do that in this json?
I successfully read response.docs , but then can't reach id and groups_id_ss.
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"object_type_s:USER",
"indent":"true",
"wt":"json"
}
},
"response":{
"numFound":13,
"start":0,
"docs":[
{
"id":"sanja",
"groups_id_ss":[
"COORDINATION AO",
"ACM_INVESTIGATOR_DEV"
]
},
{
"id":"sanjaseconduser",
"groups_id_ss":[
"ACM_SUPERVISOR_DEV",
"CHAIRMAN",
"ACM_ADMINISTRATOR_DEV",
"CPC INITIATOR",
"COORDINATION AO",
"ACM_INVESTIGATOR_DEV"
]
}
]
}
}
As stated you could read response.docs from json. Let's say
var docs = response.docs;
As docs is an array you can use forEach to loop thruogh each element
docs.forEach(function(doc) {
if(doc.id === "desired_Id") {
var groupIdSS = doc.groups_id_ss;
}
});
This way you can read groups_id_ss for desired id.
Hope it helps.
Since you are using the values in separate file, you can use like this.
I am assuming the file is stored as .json
For example, your json values are in response.json
You can write code like this in your spec file:
var responseData = require('../../response.json');
describe('some function description', function(){
var groupID = responseData.response.docs[0].groupid_ss[0];
var groupID = responseData.response.docs[0].groupid_ss[0]
});
Since that is json array, we have to give the index of the array in that.
Hope this would work for you.
I'm using Parse.com as my backend and after Query how can I fill an array with all the data inside the Parse object? how can I avoid re-mapping? example:
$scope.addContList = contacts.map(function(obj) { // re-map!!!!
return {name: obj.get("name")}; // mapping object using obj.get()
});
I'm mapping my Parse object's properties one by one: name: obj.get("name"), etc. is there a better way?
$scope.addContList = [];
var ActivityContact = Parse.Object.extend("ActivityContact2");
var query = new Parse.Query(ActivityContact);
query.equalTo("activityId", $scope.objId);
query.find({
success: function(contacts) {
console.log("Successfully retrieved " + contacts.length + " contact.");
$scope.$apply(function() {
/*$scope.addContList = contacts.map(function(obj) {
return {name: obj.get("name")}; // mapping object using obj.get()
});*/
for (var i = 0; i < contacts.length; i++) {
$scope.addContList.push(contacts.ALL_PROPERTIES); // contacts.ALL_PROPERTIES does not exist, I'm looking a way to do that and avoid mapping?
}
});
console.log("--->>>"+JSON.stringify($scope.addContList, null, 4));
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
Should I use Underscore library, is that the only way to go?
I have seen some ppl using PFQuery but I don't know what is that, is PFQuery better for this?
Thanks!
The other answers are correct, but I think it's unnecessary to launch a digest cycle every time you add an item from contacts to $scope.addContList. Something like this should be sufficient:
query.find({
success: function (contacts) {
$scope.apply(function () {
// 1) shallow-copy the list of contacts...
// (this is essentially what you are trying to do now)
$scope.addContList = contacts.slice();
// or 2) just assign the reference directly
$scope.addContList = contacts;
// or 3) transform the Parse.Object instances into
// plain JavaScript objects
$scope.addContList = contacts.map(function (c) {
return c.toJSON();
});
});
},
error: function (object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
Options 1) and 2) will correspond to a template similar to
<div ng-repeat="cont in addContList">{{ cont.get('name') }}</div>
while option 3) can be used like
<div ng-repeat="cont in addContList">{{ cont.name }}</div>
If you change
$scope.addContList = contacts[i];
to:
$scope.addContList.push(contacts[i]);
you should be good to go. Your previous code was re-assigning addContList to be each element in the contacts array, instead of adding the element to it. So at the end of your for loop, $scope.addContList would just be the last contact in your contacts array.
Change:
$scope.addContList = contacts[i];
to
$scope.addContList.push(contacts[i]);
This question already has an answer here:
Store an array with chrome.storage.local
(1 answer)
Closed 7 years ago.
So I'm in a bit of a dillema right now. I can't seem to be able to add an Array in chrome.storage and later retrieving it. Here's the code I have right now:
function() {
chrome.storage.sync.get({ObjectName: []}, function (result) {
var ObjectName = result.ObjectName;
ObjectName.push({ArrayName: document.getElementById("field")});
});
Now to retrieve it and display it:
chrome.storage.sync.get({ArrayName: function(value) {
for(i=0; i<value.length; i++) {
document.write(value)
};
The error I am getting, which might be as simple as a syntax issue, amounts to:
Error: Invocation of form get(object) doesn't match definition get(optional string or array or object keys, function callback)
You have to use set method to set values to chrome.storage
Here's an example of how to do it
To store an array to chrome storage using set
var testArray=["test", "teste", "testes"];
chrome.storage.sync.set({
list:testArray
}, function() {
console.log("added to list");
});
To get the arrayValue using get and modify if by calling updatemethod
chrome.storage.sync.get({
list:[]; //put defaultvalues if any
},
function(data) {
console.log(data.list);
update(data.list); //storing the storage value in a variable and passing to update function
}
);
function update(array)
{
array.push("testAdd");
//then call the set to update with modified value
chrome.storage.sync.set({
list:array
}, function() {
console.log("added to list with new values");
});
}
I have a user specified JSON object that I'm attempting to process in the browser.
The problem is that it needs to match an existing object.
They can't accidentally:
forget to include some fields.
typo fields or deliberately add new fields.
Is there a way to handle this?
so basically if I have an object with foo and bar members, I want their defaults if the user's json is just {} ... and if they accidentally send something like {bart: "asdf";} (typo on 'bar') then I want it to generate an exception.
var default_object = { ... };
var allowed_keys = [ "key1", "key2", ... ];
var new_object = default_object.clone();
for (var key in json_object) {
if (json_object.hasOwnProperty(key)) {
if (allowed_keys.indexOf(key) == -1) {
// Report error here
} else {
new_object[key] = json_object[key];
}
}
}
See here for how to write the clone method I used above. If you use jQuery, you could simplify some of this code by using $.extend().
I have this json file, and I'm turning into a json array, everything works fine, but the real json file contains more data.
How to simplify this code could either change the javascript or json file.
{
"Subject1":{
"Biology":{
"Category":{
"Cell":{
"question1":{
"que1":"what's....?"
},
"question2":{
"que2":"what's....?"
},
"question3":{
"que3": "what's....?"
}
},
"Bactery":{
"question1":{
"que1":"what's....?"
},
"question2":{
"que2": "what's....?"
},
"question3":{
"que3": "what's....?"
}
}
}
}
}
}
this is my code witch convert the file json into array json of javascript:
var exa = [];
function show() {
$.getJSON('questions.json', function (json) {
for (var key in json) {
if (json.hasOwnProperty(key)) {
var item = json[key];
exa.push({
//I want to simplify this part, because the real json file have more questions
que1: item.Biology.Category.Cell.question1.que1,
que2: item.Biology.Category.Cell.question2.que2,
que3: item.Biology.Category.Cell.question3.que3,
que11: item.Biology.Category.Bactery.question1.que1,
que12: item.Biology.Category.Bactery.question2.que2,
que13: item.Biology.Category.Bactery.question3.que3
});
}
}
//return Books;
console.log(exa)
})
}
Instead of que1, que2, etc., just have the questions in an array
"Cell": [
"what's this?",
"what's that?"
]
You can use json-path and write JsonPath.read(json, "$..question"); to get all questions. You need to change all que[*] in your file to question too.