I get a JSON from my sequelize function. This i have to modify, because i have to send it to a database importer, who needs it in a fixed form.
Is there a way to customize this function so that I get back the desired result ?
models:
User.associate = function (models) {
User.hasMany(models.SurveyResult)
}`
SurveyResult.associate = function (models) {
SurveyResult.belongsTo(models.User)
The function:
async mediImport (req, res) {
try {
const transaction = await User.findAll({
where: { released: true },
// Select forename as Vorname, name as Nachname
attributes: [
['forename', 'PAPPS286'],
['name', 'Nachname'],
['birthdate', 'PADPS60']
],
include: [{ model: SurveyResult, attributes: ['result'] }]
}).map(user => user.toJSON())
res.send({
transaction
}
)
}
this is the JSON which i get from the function:
{
"transaction": [
{
"PAPPS286": "Tes",
"Nachname": "Josef",
"PADPS60": null,
"SurveyResults": [ {
"result": {
"name": "blau",
"email": "mail",
"birthdate": "01.02.1990"
}
}]
},
{
"PAPPS286": "Dampf",
"Nachname": "Hans",
"PADPS60": null,
"SurveyResults": [
{
"result": {
"name": "blau",
"email": "mail",
"birthdate": "01.02.1990"
}
}
]
},
]
},
This is the JSON form i need:
{
"transaction": [
PAD{
"PAPPS286": "Tes",
"Nachname": "Josef",
"PADPS60": null,
"MH": {
"name": "blau",
"email": "mail",
"birthdate": "01.02.1990"
},
PAD{
"PAPPS286": "Dampf",
"Nachname": "Hans",
"PADPS60": null,
"MH": {
"name": "blau",
"email": "mail",
"birthdate": "01.02.1990"
}
},
]
},
Perhaps there is a way to modify the JSON after i get it back. But i dont Knoe how this can be work.
The below map does what I think you are looking for. You may need to modify it, especially around accessing the variables you need, based on the key. (t.PAPPS286 and t.PADPS60)
Additionally, I am only grabbing the first survey result SurveyResults. Unsure what you want if there are none or if there are more than 1.
var obj = {
"transaction": [{
"PAPPS286": "Tes",
"Nachname": "Josef",
"PADPS60": null,
"SurveyResults": [{
"result": {
"name": "blau",
"email": "mail",
"birthdate": "01.02.1990"
}
}]
},
{
"PAPPS286": "Dampf",
"Nachname": "Hans",
"PADPS60": null,
"SurveyResults": [{
"result": {
"name": "blau",
"email": "mail",
"birthdate": "01.02.1990"
}
}]
},
]
}
obj.transaction = obj.transaction.map((t) => {
return Object.assign({
"PAPPS286": t.PAPPS286,
"Nachname": t.Nachname,
"PADPS60": t.PADPS60,
"MH": {
"name": t.SurveyResults[0].result.name,
"email": t.SurveyResults[0].result.email,
"birthdate": t.SurveyResults[0].result.birthdate
}
})
})
console.log(obj);
Related
Lets say I have a JSON file with an array in it like this:
[
{
"distinct_id": "abc",
"properties": {
"bookID": "123",
"userID": "abc",
}
},
{
"distinct_id": "abc",
"properties": {
"bookID": "123",
"userID": "abc",
}
},
{
"distinct_id": "ced",
"properties": {
"bookID": "123",
"userID": "ced",
}
},
{
"distinct_id": "abc",
"properties": {
"bookID": "456",
"userID": "ced",
}
}
]
I am trying to figure out how I would loop through this and return a new array just one instance of each distinct_id (basically removing duplicates) - think of it like a an array of unique users.
I am using TypeScript. I was trying to use Set but that wasn't working.
interface Item {
distinct_id: string;
properties: {
bookID: string;
userID: string;
};
}
const getDistinctIds = (data: Item[]) => data.map(item => item.distinct_id);
const getUniqueDistinctIds = (data: Item[]) => Array.from(new Set(getDistinctIds(data)));
const getItemByDistinctId = (data: Item[], distinct_id: string) => data.find(item => item.distinct_id === distinct_id);
const getUniqueItems = (data: Item[]) => getUniqueDistinctIds(data).map(distinct_id => getItemByDistinctId(data, distinct_id));
const data: Item[] = [
{
"distinct_id": "abc",
"properties": {
"bookID": "123",
"userID": "abc",
}
},
{
"distinct_id": "abc",
"properties": {
"bookID": "123",
"userID": "abc",
}
},
{
"distinct_id": "ced",
"properties": {
"bookID": "123",
"userID": "ced",
}
},
{
"distinct_id": "abc",
"properties": {
"bookID": "456",
"userID": "ced",
}
}
];
const uniqueItems = getUniqueItems(data);
console.log(uniqueItems);
Here is link to TS PLAYGROUND
I have a json like this:
{
"data": [
{
"id": "99412",
"type": "post_list_item",
"attributes": {
"message": "#:user/3 \n#:user/77 \n#:user/52 #:user/3921 #:user/267 #:user/5 \n\nWhich sector will outperform in 2023 ???",
"visibility": "public_visible",
"created_at": "2023-01-07T14:38:00.691+05:30",
"updated_at": "2023-01-07T14:38:00.779+05:30",
"meta_info": null,
"type": "Post",
"likes_count": 8,
"replies_count": 2,
"widgets_data": [],
"is_liked": false,
"is_bookmarked": false,
"is_deleted": false,
"share_count": null
},
"relationships": {
"user": {
"data": {
"id": "86806",
"type": "user"
}
},
"poll": {
"data": {
"id": "483",
"type": "poll"
}
},
"tagged_users": {
"data": [
{
"id": "3",
"type": "user"
},
{
"id": "5",
"type": "user"
},
{
"id": "52",
"type": "user"
},
{
"id": "77",
"type": "user"
},
{
"id": "267",
"type": "user"
},
{
"id": "3921",
"type": "user"
}
]
},
"tagged_companies": {
"data": []
},
"tagged_topics": {
"data": []
},
"tagged_instruments": {
"data": []
},
"stories": {
"data": []
},
"attachments": {
"data": []
},
"media_files": {
"data": []
}
}
},
{
"id": "99548",
"type": "post_list_item",
"attributes": {
"message": "๐๐จ๐ฉ ๐ง๐๐ฐ๐ฌ ๐ญ๐จ๐๐๐ฒ๐ \n\n๐SGX Nifty up by 132 pts indicating a strong open
today. FIIs sold Rs 29 Bn while DIIs bought Rs 10.8 Bn of stocks on Friday.\n\n๐India surpasses Japan to become world's 3rd largest auto market in 2022: SIAM report\n\n๐Dr Lal PathLabs, leader in North India, expands in West India. Subsidiary opens apex lab in Mumbai - all nearby samples to be tested here instead of Delhi (positive).\n\n๐IL&FS pays 5 PSU Banks 87% of their โน1,500 crore dues. Canara, Union Bank, Central, Punjab & Sind Bank.\n\n๐EV scooter co. Ather Energy to achieve $1 billion in revenue in 2023 and turn profitable in few years. Beneficiary: Hero Motors\n\n๐Outstanding dues by power distributors (discoms) to producers (gencos) has nearly halved to Rs 62,681 cr in last 1 year. Benficiary: PFC, REC (but priced in).\n\n๐Solar panel manufacters boost production as costs fall for polysilicon and wafer (RM for solar cells). Positive for Sterling Wilson Renewables, Borosil Renewables.\n\n1/2",
"visibility": "public_visible",
"created_at": "2023-01-09T09:05:41.226+05:30",
"updated_at": "2023-01-09T09:05:41.277+05:30",
"meta_info": null,
"type": "Post",
"likes_count": 4,
"replies_count": 1,
"widgets_data": [],
"is_liked": false,
"is_bookmarked": false,
"is_deleted": false,
"share_count": null
},
"relationships": {
"user": {
"data": {
"id": "83681",
"type": "user"
}
},
"poll": {
"data": null
},
"tagged_users": {
"data": []
},
"tagged_companies": {
"data": []
},
"tagged_topics": {
"data": []
},
"tagged_instruments": {
"data": []
},
"stories": {
"data": []
},
"attachments": {
"data": []
},
"media_files": {
"data": []
}
}
}, ],
"included": [
{
"id": "86806",
"type": "user",
"attributes": {
"display_name": "Ravi Gupta",
"username": "ravigupta132",
"dp_thumbnail": "/rails/active_storage/representations/proxy/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBBZ2E4IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--763b2ccc4372862bb99de6620aa9fe9661693603/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaDdCem9MWm05eWJXRjBTU0lJYW5CbkJqb0dSVlE2RkhKbGMybDZaVjkwYjE5c2FXMXBkRnNIYVFHQWFRR0EiLCJleHAiOm51bGwsInB1ciI6InZhcmlhdGlvbiJ9fQ==--7b4a499a9ad66d05dd5deec71f9adfd36a29feb5/image_cropper_1672468958147.jpg",
"market_view": "neutral"
},
"relationships": {}
},
{
"id": "483",
"type": "poll",
"attributes": {
"question": "#:user/3 \n#:user/77 \n#:user/52 #:user/3921 #:user/267 #:user/5 \n\nWhich sector will outperform in 2023 ???",
"options": [
"Metal",
"PSU banks",
"IT",
"Infrastructure"
],
"vote_count": 52,
"grouped_count": null,
"ends_at": "2023-01-14T14:38:01.760+05:30",
"my_vote": null,
"is_expired": false
},
"relationships": {
"base_post": {
"data": {
"id": "99412",
"type": "post"
}
}
}
}, ]
}
Basically, 2 lists in an object.
I am unable to deserialize this data. How do I de-serialize this data to get 2 lists? I need to get data based on a common id.
This is what I have currently (WIP):
Future<List<Datum>> getPostData() async {
try {
Response response = await _dio.get(url);
var jsonData = response.data;
//Map<String, dynamic> postMap = response.data;
final someMappedObjectList = <Datum>[];
for (var map in jsonData["data"]) {
Datum someObject = Datum(
id: map["id"],
type: map["type"],
attributes: map["attributes"],
relationships: map["relationships"]);
//final someObject = Datum.fromJson(map);
someMappedObjectList.add(someObject);
}
//List<dynamic> listDatum = postMap["data"].toList();
//List<Datum> listDatum = Datum.fromJson(jsonData["data"]) as List<Datum>;
return someMappedObjectList;
} //
catch (e) {
print(e);
return [];
}
}
Future<List> getPostIncluded() async {
try {
Response response = await _dio.get(url);
var jsonData = response.data;
Map<String, dynamic> postMap = response.data;
List<dynamic> listIncluded = postMap["included"].toList();
return listIncluded;
} //
catch (e) {
print(e);
return [];
}
}
Especially for something this complex, I strongly suggest using the json_serializable package. It will save you quite a bit of trouble in the long term.
{
"kind": "identitytoolkit#GetAccountInfoResponse",
"users": [
{
"localId": "XR9iEJd8SpWLZyIlTclB77lquz52",
"email": "abdulrehmansnp57#gmail.com",
"passwordHash": "UkVEQUNURUQ=",
"emailVerified": false,
"passwordUpdatedAt": 1666284051842,
"providerUserInfo": [
{
"providerId": "password",
"federatedId": "abdulrehmansnp57#gmail.com",
"email": "abdulrehmansnp57#gmail.com",
"rawId": "abdulrehmansnp57#gmail.com"
}
],
"validSince": "1666284051",
"lastLoginAt": "1666346094257",
"createdAt": "1666284051842",
"lastRefreshAt": "2022-10-21T09:54:54.257Z"
}
]
}
If I understood your question correctly, you want to return the "localId", but since it's an array I will assume you will have multiple users. So here's an example of how you can return an array of the "localId" in react or JavaScript in general:
const obj= { "kind": "identitytoolkit#GetAccountInfoResponse", "users": [ { "localId": "XR9iEJd8SpWLZyIlTclB77lquz52", "email": "abdulrehmansnp57#gmail.com", "passwordHash": "UkVEQUNURUQ=", "emailVerified": false, "passwordUpdatedAt": 1666284051842, "providerUserInfo": [ { "providerId": "password", "federatedId": "abdulrehmansnp57#gmail.com", "email": "abdulrehmansnp57#gmail.com", "rawId": "abdulrehmansnp57#gmail.com" } ], "validSince": "1666284051", "lastLoginAt": "1666346094257", "createdAt": "1666284051842", "lastRefreshAt": "2022-10-21T09:54:54.257Z" } ] };
const ids= obj.users.map((e)=>e.localId);
response: ids=[XR9iEJd8SpWLZyIlTclB77lquz52];
New to programming...probably a stupid question...
I have a users.json file.
{
"User": {
"userID": [
{
"$": {
"id": "3"
},
"username": [
"patient1"
],
"email": [
"x#gmail.com"
],
"Role_IDrole": [
"1"
],
"Organization": [
"1"
],
"Lat": [
"59.6567"
],
"Long": [
"16.6709"
]
}
]
}
}
I am requiring it in my routes
var userData = require('../users.json');
My route
app.get('/doctor', isLoggedIn, function(req, res) {
res.render('doctortest.ejs', {
user : req.user,
data: userData
});
});
In my views/doctortest.ejs, I simply want to print the "email"
<%data.User.userID.email%>
It doesn't show anything. What's going on?
I have a simple json file:
val myJson = {
"field1": [
{
"name": "john",
"lname": "knight"
},
{
"name": "jack",
"lname": "samuel"
},
{
"name": "elinor",
"lname": "cooper"
}
],
"field2": [
{
...
},
{
...
},
{
...
}
],
"field3": [
{
...
},
{
...
},
{
...
}
]
}
and what i want is to be able to iterate on "field1" and for each name to call a method that returns some value and insert this value to the json under "fiel1".
// this returns a list of strings
val kids = getKids("john")
// this is will me the returned value
kids = List("amy", "tom")
now I want to insert it:
{
"field1": [
{
"name": "john",
"lname": "knight"
"kids": ["amy", "tom"]
},
{
"name": "jack",
"lname": "samuel"
"kids": ["edi", "keren"]
},
{
"name": "elinor",
"lname": "cooper"
"kids": ["lilly", "mag"]
}
]
...
but I want to iterate on all the names and do this for each one...how can I accomplish this with json4s?
so lets say i have the parsed json:
val myParsedJson = JsonMethods.parse(myJson)
how do I go from here?
thanks!