currently i have an api in which you send a json and the api response:
the json i send: {
"instructions": [
{
"A": 9,
"B": 1,
"move": "moveonto"
},
{
"A": 8,
"B": 1,
"move": "moveover"
}
],
"length": 20,
"res": "null"
}
and the api response: {
"instructions": [
{
"A": 9,
"B": 1,
"move": "moveonto"
},
{
"A": 8,
"B": 1,
"move": "moveover"
}
],
"length": 20,
"res": "Position [0] : 0Position [1] : 1 9 8Position [2] : 2Position [3] : 3Position [4] : 4Position [5] : 5Position [6] : 6Position [7] : 7Position [8] : Position [9] : Position [10] : 10Position [11] : 11Position [12] : 12Position [13] : 13Position [14] : 14Position [15] : 15Position [16] : 16Position [17] : 17Position [18] : 18Position [19] : 19"
}
im developing a very basic webpage:
when i click on the send to the server button i need to send it, the problem is i dont know how to build the json, can you help me? thx
i have slight idea:
Json = {
"instructions": [{
"A": $scope.addA,
"B": $scope.addB,
"move": $scope.addMov
}, {
"A": $scope.addA,
"B": $scope.addB,
"move": $scope.addMov
}],
"length": $scope.blockLength,
"res": null
};
and i send it :
$http.post("http://localhost:56493/api/BlocksProblem", Json)
.then(function (data) {
$scope.result = data;
}, function (response) {
$scope.result = response;
});
thank you very much for your time reading through all of it.
You dont necessarily "build" the json in the typical sense. By sending object data, angularjs with convert it to json for you.
for example. If i have a javascript variable like this:
var J = {A:1, B:2}
and send it as data in an http post, the json would look like:
{"A":"1","B":"2"}
Without seeing anything of what your server architecture looks like, you could do something like this
$scope.SendJson = function (Callback) {
$http({
url: YOURURL,
method: 'POST',
dataType: 'json',
data: {
"instructions": [
{"A": $scope.addA,"B": $scope.addB,"move": $scope.addMov},
{"A": $scope.addA,"B": $scope.addB,"move": $scope.addMov}],
"length": $scope.blockLength,
"res": null}
})
.then(function (data) {
$scope.result = data;
}, function (response) {
$scope.result = response;
});
})
Also, you dont need to quote the key value. Its implicit
With all that said, verify that the packet is constructed correctly in your developer tools.
reading through stackoverflow i found this:
How do I create JavaScript array (JSON format) dynamically?
so i build mine with:
//here i save the values of A,B and the moves, that i get from the form
var serverMove = [];
var serverA = [];
var serverB = [];
//create the json
var jsonS = {
instructions: [],
"length": $scope.blockLength,
"res": ""
};
//dynamically fill only the instrucions array part
for (var i = 0; i < serverA.length; i++) {
jsonS.instructions.push({
"A": serverA[i],
"B": serverB[i],
"move": serverMove[i]
})
}
the result json is something like :
{
"instructions": [
{
"A": 1
, "B": 3,
"move":
"moveonto"
},
{
"A": 5,
"B": 9,
"move": "pileover"
}
],
"length": 22,
"res": ""
}
i hope someone finds it useful
Related
I'm trying to append the JSON data at a specific index but it's not working. The JSON data is-
a = {resourceTypeId: "tmf.resourceTypes.TmfServiceInterface", transitions: [2], states: null}
There are 2 arrays in transitions
transitions: [2]
0: {…}
stateFrom: "initial"
stateTo: "feasibilityChecked"
name: "checkFeasibility"
operationName: "checkServiceFeasibility"
1: {…}
stateFrom: "initial"
stateTo: "designed"
name: "design"
operationName: "designService"
I'm trying to append the 3rd array in transitions
b = {
"name": "deleteaaa",
"operationName": "Serviceaa",
"stateFrom": "test",
"stateTo": "test"
}
I've tried this-
c = a.transitions.concat(b)
It's adding the 3rd array in transitions but not getting Other data like resourceTypeId: "tmf.resourceTypes.TmfServiceInterface" and states: null
The expected data should be after merging b into a
c = {resourceTypeId: "tmf.resourceTypes.TmfServiceInterface", transitions: [3], states: null}
Pls, assist.
you maybe want this
a.transitions = a.transitions.concat(b)
var a = {
"resourceTypeId": "tmf.resourceTypes.TmfServiceInterface",
"transitions": [
{
"stateFrom": "initial",
"stateTo": "feasibilityChecked",
"name": "checkFeasibility",
"operationName": "checkServiceFeasibility"
},
{
"stateFrom": "initial",
"stateTo": "designed",
"name": "design",
"operationName": "designService"
},
{
"name": "deleteaaa",
"operationName": "Serviceaa",
"stateFrom": "test",
"stateTo": "test"
}
],
"states": null
}
var b = {
"name": "deleteaaa",
"operationName": "Serviceaa",
"stateFrom": "test",
"stateTo": "test"
}
a.transitions = a.transitions.concat(b)
console.log(a)
example
I'm trying to convert a json response code, but i keep getting a back a string array instead.
The header fields are depending on the table I query, so I cannot hardcode these.
I get a json response like:
{
"records": [
[
1,
"page one",
300
],
[
2,
"page 2",
500
]
],
"header: [
"page_id",
"page_name",
"total"
]
}
But i would like to convert this to
{
[
{
"page_id": 1,
"page_name": "page one",
"total": 300
},
{
"page_id": 2,
"page_name": "page 2",
"total": 500
}
]
}
I tried to create an Array and converting this to json but it still returns a string array, instead of a json array
let array = new Array;
records.forEach((record) => {
const parts = [];
let i = 0;
header.forEach((title) => {
const part = title + ': ' + record[i];
parts.push(part);
i++;
});
array.push(JSON.parse(JSON.stringify(parts)));
});
console.log(array) // Shows a string array?
I would expect
{
[
{
"page_id": 1,
"page_name": "page one",
"total": 300
},
{
"page_id": 2,
"page_name": "page 2",
"total": 500
}
]
}
But actual
[
[ 'page_id: 1', 'page_name: page 1', 'total: 300'],
[ 'page_id: 2', 'page_name: page 2', 'total: 500']
]
The issue with the way you are doing it, is you are creating an array and pushing the values onto it, where what you want to do is create the array and push objects onto it that contain your values...
This can be done with a small amount of code using map (documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map)
results.records.map((arr)=> ({
page_id: arr[0],
page_name: arr[1],
total: arr[2]
});
You can also deconstruct it like so
results.records.map(([page_id, page_name, total])=> ({
page_id,
page_name,
total,
});
/*jshint esversion: 6 */
let records = {
"records": [
[
1,
"page one",
300
],
[
2,
"page 2",
500
]
],
"header": [
"page_id",
"page_name",
"total"
]
};
let arr1 = records.header.map(data => data + ":");
let finalarray = new Array(10);
var keys = arr1;
var values = records.records;
finalarray = [];
values.forEach((data,index) =>{
var objJSON = new Object({});
for (i = 0; i < keys.length; i++) {
objJSON[keys[i]] = data[i];
}
finalarray.push(objJSON);
});
console.log(finalarray);
I have stored your given data in records object and then mapped the headers with colon ":" and in second loop I have joined both arrays in json object.
Output is now:
[ { 'page_id:': 1, 'page_name:': 'page one', 'total:': 300 },
{ 'page_id:': 2, 'page_name:': 'page 2', 'total:': 500 } ]
I've a response data in array object
here my response code :
{
"data": [
{
"id": 7,
"product_name": "iPad",
"rating": "4.00"
},
{
"id": 2,
"product_name": "iPhone",
"rating": "3.00"
},
{
"id": 8,
"product_name": "iPod",
"rating": "7.00"
},
{
"id": 4,
"product_name": "iMac",
"rating": "9.00"
}
],
"status": 200,
"error": 0
}
and then i try to map the array object to parse the data 'rating' to integer, here my axios code :
getCustomerType: function(store) {
this.loading = true
let headers = {
Authorization: 'Bearer ' + window.accessToken
}
axios({
method: 'GET',
url: baseApi(this.selectedStore.url_id, 'en', 'customertype'),
params: this.params,
headers: headers
})
.then(response => {
this.customerTypeData = response.data.data
for (let index = 0; index < this.customerTypeData.length; index++) {
this.customerTypeData.rating[index] = parseInt(this.customerTypeData.rating[index])
}
this.loading = false
})
}
But the code of parseInt it doesn't make it solve
for (let index = 0; index < this.customerTypeData.length; index++) {
this.customerTypeData.rating[index] = parseInt(this.customerTypeData.rating[index])
}
Expected :
rating (by index) it change from string to number by index array
node v7.7.1
mongodb: 2.2.33,
mongoose: 4.13.7
Hello all,
i'm having this unexpected behaviour when trying to update a document with multiple pull request based on matching criterias. here is what i mean
my document schma looks like this
{
"_id": "5a1c0c37d1c8b6323860dfd0",
"ID": "1511781786844",
"main": {
"_id": "5a3c37bfc065e86a5c593967",
"plan": [
{
"field1": 1,
"field2": 1,
"_id": "5a3c30dfa479bb4b5887e56e",
"child": []
},
{
"field1": 1,
"field2": 2,
"_id": "5a3c30e1a479bb4b5887e5c",
"child": []
},
{
"field1": 1,
"field2": 3,
"_id": "5a3c37bfc065e86a5c593968",
"child": []
},
{
"field1": 1,
"field2": 4,
"_id": "5a3c37bfc065e86a5c593655",
"child": []
},
{
"field1": 1,
"field2": 5,
"_id": "5a3c30dfa479bb4b5887e56f",
"child": []
},
{
"field1": 1,
"field2": 6,
"_id": "5a3c30e1a479bb4b6887e545",
"child": []
},
{
"field1": 1,
"field2": 7,
"_id": "5a3c37bfc065e86a5c5939658",
"child": []
},
{
"field1": 2,
"field2": 2,
"_id": "5a3c37bfc065e86a5c593963",
"child": []
},
]
},
...
....
}
and this is my code to update the document:
Schema.findOne({ID: data.ID})
.then(function(doc) {
var array = doc.main.plan;
for (i = 0; i < array.length; i++) {
if ( array[i].field1=== 1 )) {
var id = array[i]._id;
console.log('pulling');
doc.pull( { _id: id });
}
}
doc.save().then(function(doc) {
console.log('saving');
// console.log(doc);
if (doc && doc.docID) {
return { success: true };
} else {
return { success: false, error: 'unknownError'}
}
})
}
now the issue is let's say my array has 7 objects that matches the test (array[i].theField === parseInt(updFields.theField)), when i run this and check the logs i see that it will basically pull half of the objects and do a save.
so i would get
pulling
pulling
pulling
pulling
save.
and then i have to run the code for the remaining 3 objects in the array and get
pulling
pulling
saving
so i have to run it a third time to completely clear the array.
need help get this working
thank you
So i created a little workaround by doing a recursive function to pull all with only one click using lodash functions. not pretty but it does the job.
const delObjArray = (doc, cond) => {
const checkField = cond.field;
const checkVal = cond.value;
_.forEach(doc, (value) => {
if (value && value[checkField] === checkVal) {
doc.pull({ _id: value._id });
}
});
const isFound = _.some(doc, { [checkField]: checkVal });
if (isFound) {
delObjArray(doc, cond);
} else {
return true;
}
return true;
};
If I have a response of this kind:
{
"A": 2,
"B": [
{
"CCC": "abcde",
"DDD": {
"EEE": 11,
"FFF": 22
}
},
{
"CCC": "fghij",
"DDD": {
"EEE": 111,
"FFF": 222
}
}
]
}
how can I get all the values CCC in a list or otherwise?
If I use:
.check(jsonPath("$..CCC").saveAs("VARIABLE"))
I only get the first CCC ("abcde"). Doing it via CCC[*] throws an error.
I think, you should have to add findAll in check statement.
for example:
.check(jsonPath("$..[*].CCC").findAll.saveAs("VARIABLE"))
And please define your error.
Cheers,
Peekay