converting json format to work with d3 - arrays

I am having problems formatting json to suit my needs for d3.
This is the incoming json.
{
"success": true,
"terms": "https://currencylayer.com/terms",
"privacy": "https://currencylayer.com/privacy",
"timeframe": true,
"start_date": "2010-03-01",
"end_date": "2010-03-04",
"source": "USD",
"quotes": {
"2010-03-01": {
"USDCAD": 1.31
},
"2010-03-02": {
"USDCAD": 1.32
},
"2010-03-03": {
"USDCAD": 1.34
}
}
}
i need to format it somehow to resemble the array below.
[
{"date":"2010-03-01","USDCAD": 1.31},
{"date":"2010-03-02","USDCAD": 1.32},
{"date":"2010-03-03","USDCAD": 1.33},
]

This is what i ended up with, not sure if it is the most efficient but it works.
d3.json(./somedata.json, function (response) {
var newdata = response.quotes;
data = []
for (var i in newdata) {
var datacopy = newdata[i];
datacopy.date = i;
data.push(datacopy)
}

Related

Logic App - Refer and map fields on different JSON data sources

I have two JSON data sources:
Source Data 1:
{
"result": [
{
"resource_list": "7961b907db9253045fbdf1fabf9619d4,55617907db9253045fbdf1fabf9619d2",
"project": "11216",
"project_manager": {
"value": "55617907db9253045fbdf1fabf9619d2"
}
}
]
}
Source Data 2:
{
"result": [
{
"sys_id": "7961b907db9253045fbdf1fabf9619d4",
"email": "test.user1#mysite.com"
},
{
"sys_id": "55617907db9253045fbdf1fabf9619d2",
"email": "test.user2#mysite.com"
}
]
}
I want to reference "resource_list" and "project_manager" from Source Data 1 to "sys_id" in Source Data 2 and get "email" out from Source Data 2 and then compose a final Output like below:
Output:
[
{
"__metadata":
{
"uri": "ProjectCode"
},
"externalProject": "11216",
"projectCodeAssignment":
[
{
"__metadata":
{
"uri": "projectCodeAssignment"
},
"externalProjectAssignee": "test.user1#mysite.com"
},
{
"__metadata":
{
"uri": "projectCodeAssignment"
},
"externalProjectAssignee": "test.user2#mysite.com"
}
]
}
]
Is this possible to get this done entirely in Logic App without using Function App or anything to perform it rather.
I write a js script for you. For a quick demo, I omitted some data related to __metadata, seems that is some hard code, not so important here. Try Logic below:
Code in JS code action:
var body = workflowContext.trigger.outputs.body
var data1 = body.data1;
var data2 = body.data2;
var result = [];
data1.result.forEach(item =>{
var resultItem = {};
resultItem.externalProject = item.project;
resultItem.projectCodeAssignment =[];
var resourceIds = item.resource_list.split(',');
resourceIds.forEach(id =>{
var user = data2.result.find( ({ sys_id }) => sys_id === id );
resultItem.projectCodeAssignment.push({"externalProjectAssignee": user.email})
});
result.push(resultItem);
})
return result;
Request Body(your 2 data set are named as data1 and data2 here ):
{
"data1": {
"result": [{
"resource_list": "7961b907db9253045fbdf1fabf9619d4,55617907db9253045fbdf1fabf9619d2",
"project": "11216",
"project_manager": {
"value": "55617907db9253045fbdf1fabf9619d2"
}
}
]
},
"data2": {
"result": [{
"sys_id": "7961b907db9253045fbdf1fabf9619d4",
"email": "test.user1#mysite.com"
}, {
"sys_id": "55617907db9253045fbdf1fabf9619d2",
"email": "test.user2#mysite.com"
}
]
}
}
Result:

How can I remove all JSON objects that have a certain key/value pair from an array of JSON objects?

I want to filter a dataset this like:
For example here's some fake dataset:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Donna",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Tia",
"hasChildren": false,
"livesInCity": false,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tuxedo"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
I want to filter out everything that has "livesInCity": false:
[
{
"name": "Sakura",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna", "Milk"],
"type": "tabby"
}
]
},
{
"name": "Linn",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Luna"],
"type": "tabby"
}
]
},
{
"name": "Dora",
"hasChildren": false,
"livesInCity": true,
"pets": [
{
"cats": ["Artemis", "Milk"],
"type": "tuxedo"
}
]
}
]
How can I do this? Is this possible?
In python I believe it's something like this, but I do not know how to get started in Swift:
people = [person for person in people if person.livesInCity == True]
Also, how can I filter this data set above to look like this - I want to categorize by type in name.
{
"tabby": ["Sakura", "Linn"],
"tuxedo": ["Dora"],
}
Any help will be very appreciated!
As already mentioned in the comments, you can't work directly on JSON objects in Swift. They need to be converted first.
You can parse your JSON to a Swift object and then perform filtering, grouping etc.
struct Person: Codable {
let name: String
let hasChildren: Bool
let livesInCity: Bool
let pets: [Pet]
}
struct Pet: Codable {
let cats: [String]
let type: String
}
let jsonStr = "[{"name": "Sakura", ..." // your JSON string
let jsonData = jsonStr.data(using: .utf8)!
let parsedObjects = try! JSONDecoder().decode([Person].self, from: data)
Then you can filter your parsedObjects:
let filteredObjects = parsedObjects.filter({ person in person.livesInCity == true })
or in shorter (swiftier) version:
let filteredObjects = parsedObjects.filter { $0.livesInCity }
You can also try to group by pet type:
var groupedDict = [String:[String]]()
filteredObjects.forEach{ person in
person.pets.forEach { pet in
if let _ = groupedDict[pet.type] {
groupedDict[pet.type]!.append(person.name)
} else {
groupedDict[pet.type] = [person.name]
}
}
}
print(groupedDict)
//prints ["tabby": ["Sakura", "Linn"], "tuxedo": ["Dora"]]
If at any point you want to convert your objects back to JSON you can use:
let dictData = try! JSONEncoder().encode(groupedDict)
let dictStr = String(data: dictData, encoding: .utf8)!
print(dictStr)
//prints {"tabby":["Sakura","Linn"],"tuxedo":["Dora"]}
Note
For the sake of simplicity I used forced optional unwrapping (!) when decoding/encoding objects. You may want to use do-try-catch instead (to catch errors).

How to serialize api response contains list in flutter?

This is the response I am getting from server. All the properties are String and int expect data. It is a list of objects. When serializing the response it shows error. Please explain what is wrong with my code. I am from javascript background. Serialization in flutter is different from javascript.
class ResponseModel {
String image;
int row;
int column;
int position;
List<Data> data;
ResponseModel({this.image, this.row, this.column, this.position});
factory ResponseModel.fromJson(Map<String, dynamic> parsedJson) {
return ResponseModel(
image: parsedJson['image'],
row: parsedJson['row'],
column: parsedJson['column'],
position: parsedJson['position'],
);
}
}
class Data {
String imageUrl;
Data({this.imageUrl});
factory Data.fromJson(Map<String, dynamic> parsedJson) {
return Data(imageUrl: parsedJson["imageUrl"]);
}
}
[
{
"type": "image",
"row": 1,
"column": 3,
"position":"1",
"data": [
{
"imageUrl": "https://rukminim1.flixcart.com/flap/276/294/image/6dad06016c6ab319.jpg?q=90"
},
{
"imageUrl": "https://rukminim1.flixcart.com/flap/276/294/image/9ad209b0fc3d03e4.jpg?q=90"
},
{
"imageUrl": "https://rukminim1.flixcart.com/flap/276/294/image/405e10d01fae5aa5.jpg?q=90"
}
]
},
{
"type": "image",
"row": 1,
"column": 2,
"position":"3",
"data": [
{
"imageUrl": "https://rukminim1.flixcart.com/flap/414/630/image/f186565389063212.jpg?q=90"
},
{
"imageUrl": "https://rukminim1.flixcart.com/flap/414/630/image/3eda035d946b0ebf.jpg?q=90"
}
]
},
{
"type": "image",
"row": 1,
"column": 1,
"position":"2",
"data": [
{
"imageUrl": "https://rukminim1.flixcart.com/flap/1187/636/image/4436d492e2563998.jpg?q=90"
}
]
}
]
Future<dynamic> getData() async {
final response = await http.get("https://api.myjson.com/bins/1g4o04");
final parsedJson = json.decode(response.body);
final finalResponse = ResponseModel.fromJson(parsedJson);
print(finalResponse);
setState(() {
data = parsedJson;
});
}
Error image
You can use this tool and select dart Language
Its because the response is a JSON array. Which means json.decode(response.body) returns a List<dynamic> and hence the variable parsedJson is List.
You're trying to pass this List as a parameter to the ResponseModel.fromJson(Map<String, dynamic>) method which accepts a Map as the parameter.
In simple words, you're trying to pass a List where a Map is expected.
Future<dynamic> getData() async {
final response = await http.get("https://api.myjson.com/bins/1g4o04");
final parsedJson = json.decode(response.body);
List<ResponseModel> responseList = <ResponseModel>[];
parsedJson.foreach((element) {
responseList.add(ResponseModel.fromJson(element));
})
///Response list will have your data
print(responseList);
}
Your code should be something like this

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 merge into array?

Here is my array from db,
[
{
"_id": "58144e6c0c8d7534f4307269",
"doctor_id": "5813221ace684e2b3f5f0a6d",
"prescription": [
{
"_id": "58144e6c0c8d7534f430726a",
"medicine_id": "10011241343"
}
]
I want to merge with only prescription like this
[
{
"_id": "58144e6c0c8d7534f4307269",
"doctor_id": "5813221ace684e2b3f5f0a6d",
"prescription": [
{
"_id": "58144e6c0c8d7534f430726a",
"medicine_id": "10011241343"
},
"prescription": [
{
"_id": "58144e6c0c8d7534f430726a", // it should be autogenerated
"medicine_id": "10011241344"
}
]
How can I do this?
I have tried like this
var arr = data.presription
arr=req.body// which contains only medicine id
and then by
dbModel.user.findById(data._id, function(err, data) {
data.prescription = arr;
data.save(function(err) {
if (err) {
res.status(202).json({
"success": "0",
});
} else {
res.status(200).json({
"success": "1"
});
}
})
});
But it is saving the same. How can I do this?
Note: Even when I do console.log(arr) only the old data is printing.
So data.presription is an array from the start.
data.presription.push( {
"_id": "58144e6c0c8d7534f430726a",
"medicine_id": "10011241344"
});
This is NOT a merge, what you want to do is to append (or push) items into an existing array.

Resources