JSON how to get squared brackets? - arrays

I have the following code:
JSONArray array = new JSONArray();
array.put(allWaitClasses.get(0).allPairs.get(0).pair);
array.put(allWaitClasses.get(0).allPairs.get(1).pair);
array.put(allWaitClasses.get(0).allPairs.get(2).pair);
array.put(allWaitClasses.get(0).allPairs.get(3).pair);
array.put(allWaitClasses.get(0).allPairs.get(4).pair);
array.put(allWaitClasses.get(0).allPairs.get(5).pair);
json = array.toString();
What I get is the following:
[
{
"name": "User I/O"
},
{
"key": "61410583140000"
},
...
]
But what I want is squared brackets:
var data =[
[
1229904000000,
12.74
],
[
1229990400000,
115.20
],
...
Actually I want to follow the template of this API:
https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
So how can I get the squared brackets insteand of the curved ones?

you should iterate over data and push items in following way :
var arrayX = [];
$.forEach( data, function ( item ) {
arrayX .push( [
item.timestamp, item.value
] );
} )

Related

Converting a json response in nodejs

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 } ]

In Mongoose, query fields based on array

I am trying to query documents from a mongodb collection, based on array of input query parameters sent from URL.
Sample Database Data
[
{
"drawings": {
"circle": [],
"square": [
{
"id": "828",
"name": "square"
}
],
"cube": []
},
{
"drawings": {
"circle": [
{
"id": "827",
"name": "circle"
}
],
"square": [],
"cube": []
},
{
"drawings": {
"circle": [],
"square": [],
"cube": [
{
"id": "829",
"name": "cube"
}
]
}
]
Input Query Parameter:
query = ["square","cube"];
Expected Output:
[
{
"drawings": {
"circle": [],
"square": [
{
"id": "828",
"name": "square"
}
],
"cube": []
},
{
"drawings": {
"circle": [],
"square": [],
"cube": [
{
"id": "829",
"name": "cube"
}
]
}
]
Best suited Mongoose Query:
Schema.find({
$or:[
{'drawings.square':{$elemMatch:{ name:'square'}}},
{'drawings.cube':{$elemMatch:{ name:'cube'}}}
]
});
Tried Below method. But, it is not correct.
let draw = ["square","cube"];
let draw_query =[];
for (let a=0; a<draw.length;a++){
draw_query.push("{\"drawings."+ draw[a] +"\':{$elemMatch:{ name:\"" + draw[a] + "\"}}}");
}
It creates array with single quoted strings. It cannot be used.
[ '{"drawings.square":{$elemMatch:{ name:"square"}}}',
'{"drawings.cube":{$elemMatch:{ name:"cube"}}}' ]
How to generate this mongoose query dynamically? or is there any better mongoose query to achieve the expected result.
You can query it directly using dot notation so the query should look like below:
db.collection.find({
$or: [
{
"drawings.square.name": "square"
},
{
"drawings.circle.name": "circle"
}
]
})
You can build it in JS using .map(), try:
var query = ["square","cube"];
var orQuery = { $or: query.map(x => ({ [x + ".name"]: x }) ) }

How to format JSONArray with nested arrays

I wannt to access the fields in my JSONArray. The nested brackets inside the JSONArray is very troublesome. I can't see how this format is an acceptable JSONArray return value. I get an JSONException when I try to access a field (eg "rethink3__Address__c") using getJSONObject().
[
[
{
"attributes":{
"type":"rethink3__Listing__c",
"url":"\/services\/data\/v42.0\/sobjects\/rethink3__Listing__c\/a06m0000005OPb9AAG"
},
"rethink3__Address__c":null,
"Alarm_Code__c":null,
"rethink3__Bathrooms__c":0,
"rethink3__Bedrooms__c":0,
"rethink3__Size__c":0,
"Lock_Box_Code__c":null,
"Lock_Box_Location_Notes__c":null,
"_soupEntryId":1,
"_soupLastModifiedDate":1537657104801
}
],
[
{
"attributes":{
"type":"rethink3__Listing__c",
"url":"\/services\/data\/v42.0\/sobjects\/rethink3__Listing__c\/a06m0000005OPb9AAG"
},
"rethink3__Address__c":null,
"Alarm_Code__c":null,
"rethink3__Bathrooms__c":0,
"rethink3__Bedrooms__c":0,
"rethink3__Size__c":0,
"Lock_Box_Code__c":null,
"Lock_Box_Location_Notes__c":null,
"_soupEntryId":1,
"_soupLastModifiedDate":1537657104801
}
]
]
A [] = json array and {} = json object. So try this.
let myArray = [
[
{
"attributes":{
"type":"rethink3__Listing__c",
"url":"\/services\/data\/v42.0\/sobjects\/rethink3__Listing__c\/a06m0000005OPb9AAG"
},
"rethink3__Address__c":null,
"Alarm_Code__c":null,
"rethink3__Bathrooms__c":0,
"rethink3__Bedrooms__c":0,
"rethink3__Size__c":0,
"Lock_Box_Code__c":null,
"Lock_Box_Location_Notes__c":null,
"_soupEntryId":1,
"_soupLastModifiedDate":1537657104801
}
],
[
{
"attributes":{
"type":"rethink3__Listing__c",
"url":"\/services\/data\/v42.0\/sobjects\/rethink3__Listing__c\/a06m0000005OPb9AAG"
},
"rethink3__Address__c":null,
"Alarm_Code__c":null,
"rethink3__Bathrooms__c":0,
"rethink3__Bedrooms__c":0,
"rethink3__Size__c":0,
"Lock_Box_Code__c":null,
"Lock_Box_Location_Notes__c":null,
"_soupEntryId":1,
"_soupLastModifiedDate":1537657104801
}
]
];
myArray.forEach((myNestedArray)=>{
let obj = myNestedArray[0]
console.log(obj.attributes.type);
console.log(obj._soupLastModifiedDate);
})

Loop through Dictionary in Swift

I have a dictionary which I want to append some items.
**This is my dictionary which I want to achieve: **
let parameters: [String: Any] = [
{
"ResultsList": [{
"UserId": "b806e283-066f-4081-aafe-1fe216a57c35",
"FriendUserId": "7a2ec150-cdb3-4600-84f8-2dab970bfa0c",
"TransferDate": "2017-11-23",
"UserAnswers": [{
"AnswerId": "b7562603-614d-11e7-a7e0-484d7ee0cd26",
"LastAnsweredDate": "2017-11-23",
"QuestionId": "0b60f35e-5d80-11e7-a7e0-484d7ee0cd26"
},
{
"AnswerId": "b7562603-614d-11e7-a7e0-484d7ee0cd26",
"LastAnsweredDate": "2017-11-23",
"QuestionId": "0b60f35e-5d80-11e7-a7e0-484d7ee0cd26"
}
]
}]
}
]
And this is my current dictionary which I want to make the loop and add the items.
let parameters: [String: Any] = [
{
ResultsList: [
{
UserId: “b806e283-066f-4081-aafe-1fe216a57c35”
FriendUserId: “7a2ec150-cdb3-4600-84f8-2dab970bfa0c”
TransferDate: “2017-11-23”
UserAnswers: [
{
AnswerId: “b7562603-614d-11e7-a7e0-484d7ee0cd26"
LastAnsweredDate: “2017-11-23”
QuestionId : “0b60f35e-5d80-11e7-a7e0-484d7ee0cd26"
}
]
}
]
}
]
I have 3 arrays which I want to loop through and append to the dictionary
var AnswerId = [ “b7562603-614d-11e7-a7e0-484d7ee0cd26", “aasdaas-614d-11e7-a7e0-484d7ee0cd26", “b756asd03-614d-11e7-a7e0-484d7ee0cd26"]
var LastAnsweredDate = [“2017-11-23”, “2017-11-23”, “2017-11-22”]
var QuestionId = [“0b60f35e-5d80-11e7-a7e0-484d7ee0cd26",“asdasd-5d80-11e7-a7e0-484d7ee0cd26",“asdasd-5d80-11e7-a7e0-484d7ee0cd26"]
Can someone please help to achieve this result?

JavaScript (Node.js) - JSON recursion extracting objects to array with order (faltten)

I have a JSON config file as follows:
var conf = [
{
"value": "baz",
"threshold": 20,
"other": 123
},
{
"value": "mo",
"other": 456,
"child": {
"value": "foo",
"other": 789,
"child": {
"value": "larry",
"other": 123
}
}
}
];
I have a requirement to extract each of the objects and persist them together in order if they have child objects. For example, object 1 (baz) is stand alone. Object 2 (mo) will have two child objects. These 3 as a set must be extracted together.
There is no limit to the number of child objects.
Im attempting to persist each object using an array to maintain the order. So the required output would look like:
[[{"value":"baz","threshold":20,"other":123}],
[[{"value":"mo","other":456,"child":{"value":"foo","other":789,"child":{"value":"larry","other":123}}}],
[{"value":"foo","other":789,"child":{"value":"larry","other":123}}],
[{"value":"larry","other":123}]]]
A final requirement is to actually remove the child values from the parents so the output can actually be like:
[
[{"value":"baz","threshold":20,"other":123}],
[
[{"value":"mo","other":456}],
[{"value":"foo","other":789}],
[{"value":"larry","other":123}]
]
]
Ive been hung up on this for hours with little progress. I know I need to create a recursive function, push each node to an array, and then check for child object and repeat.
Heres what I have so far. My thinking is if I can take the array id each task is being pushed to (using a loop id), perhaps I can map that when the function is called again.
Appreciate any guidance.
var execSets = [];
function parser(tasks){
// an ordered array of task execution
for (let eachTask in tasks) {
var taskSet = [];
console.log("====================================");
console.log(tasks[eachTask]);
if(!tasks[eachTask].child && typeof(tasks[eachTask]) === 'object'){
console.log(tasks[eachTask]);
taskSet.push(tasks[eachTask]);
execSets.push(taskSet);
}
if(tasks[eachTask].child){
let childAlias = tasks[eachTask].child;
delete tasks[eachTask].child;
taskSet.push(tasks[eachTask]);
execSets.push(taskSet);
parser(childAlias);
}
}
}
The npm registry is your friend; try 'npm search flat,
There are a few modules that can help flatten a json object. For example https://www.npmjs.com/package/flat
You could do it using recursion. Here is my suggestion:
var conf = [
{
"value": "baz",
"threshold": 20,
"other": 123
},
{
"value": "mo",
"other": 456,
"child": {
"value": "foo",
"other": 789,
"child": {
"value": "larry",
"other": 123
}
}
}
];
function getFlattenedObject(object){
var response = [];
flatten(object, response, 0);
return response;
}
function flatten(object, array, index){
if(!array[index]){
array.push([]);
}
array[index].push(object);
if(object.child){
flatten(object.child, array, index + 1);
object.child = undefined;
}
}
//Logs for comparison
console.dir(conf)
console.dir(getFlattenedObject(conf));
The result structure you are looking for wasn't "intuitive" and hence the solution has gotten a little ugly, but here is how you could use object-scan to answer your question
// const objectScan = require('object-scan');
const data = [{"value":"baz","threshold":20,"other":123},{"value":"mo","other":456,"child":{"value":"foo","other":789,"child":{"value":"larry","other":123}}}]
const fn = (haystack) => objectScan(['[*]', '**.child'], {
filterFn: ({
key: [id, ...p],
value: { child, ...node },
context
}) => {
if (!(id in context)) {
context[id] = [];
}
context[id].push(child || p.length !== 0 ? [node] : node);
}
})(haystack, []);
console.log(fn(data));
// => [ [ { value: 'baz', threshold: 20, other: 123 } ], [ [ { value: 'larry', other: 123 } ], [ { value: 'foo', other: 789 } ], [ { value: 'mo', other: 456 } ] ] ]
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.7.1"></script>
Disclaimer: I'm the author of object-scan

Resources