Ruby API call to get data from complex json - json

I'm making an API GET call using Ruby - the call is made to a Learning Management System and returns the following JSON:
{
"id": 12345,
"body": null,
"url": null,
"grade": "75",
"score": 75,
"submitted_at": "2020-05-02T11:30:53Z",
"assignment_id": 9876,
"user_id": 1111,
"submission_type": "online_upload",
"workflow_state": "graded",
"grade_matches_current_submission": true,
"graded_at": "2017-06-05T08:47:49Z",
"grader_id": 2222,
"attempt": 1,
"cached_due_date": "2020-05-03T15:00:00Z",
"excused": false,
"late_policy_status": null,
"points_deducted": null,
"grading_period_id": null,
"late": false,
"missing": false,
"seconds_late": 0,
"entered_grade": "75",
"entered_score": 75,
"preview_url": "https://etcetc",
"turnitin_data": {
"attachment_33333": {
"status": "scored",
"object_id": "44444444",
"similarity_score": 0,
"web_overlap": 0,
"publication_overlap": 0,
"student_overlap": 0,
"state": "none"
}
},
"attachments": [
{
"id": 33333,
"uuid": "kjsdkjhsdfkhsfd",
"folder_id": 55555,
"display_name": "Submission.pdf",
"filename": "Submission.pdf",
"content-type": "application/pdf",
"url": "https://etcetc",
"size": 2668226,
"created_at": "2020-05-02T11:30:51Z",
"updated_at": "2020-06-06T15:01:46Z",
"unlock_at": null,
"locked": false,
"hidden": false,
"lock_at": null,
"hidden_for_user": false,
"thumbnail_url": null,
"modified_at": "2020-05-02T11:30:51Z",
"mime_class": "pdf",
"media_entry_id": null,
"locked_for_user": false,
"preview_url": "api/etcetc"
}
],
"submission_comments": [
{
"id": 99999,
"comment": "here’s a comment",
"author_id": 1,
"author_name": "Mickey Mouse",
"created_at": "2020-05-15T12:54:08Z",
"edited_at": null,
"avatar_path": "/images/users/1",
"author": {
"id": 1,
"display_name": " Mickey Mouse ",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
},
{
"id": 223344,
"comment": "another comment",
"author_id": 2,
"author_name": "Donald Duck",
"created_at": "2020-06-05T10:48:51Z",
"edited_at": null,
"avatar_path": "/images/users/2",
"author": {
"id": 2,
"display_name": "Donald Duck",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
}
]
}
I need to be able to retrieve specific values from "submission_comments", namely the values for "comment", "author_id" and "author_name". At the moment the best I can do is retrieve "submission_comments" as one big entity. Here's how I'm getting that far:
require 'typhoeus'
require 'link_header'
require 'json'
require 'csv'
the_url = 'https://etctetc'
token = 'mytoken'
api_endpoint = '/api/etc'
output_csv = 'C:\Users\me\Desktop\Ruby Canvas course\assignment_comments.csv'
CSV.open(output_csv, 'wb') do |csv|
csv << ["user_id", "TII", "marker"]
end
request_url = "#{the_url}#{api_endpoint}"
count = 0
more_data = true
while more_data
get_comments = Typhoeus::Request.new(
request_url,
method: :get,
headers: { authorization: "Bearer #{token}" }
)
get_comments.on_complete do |response|
#get next link
links = LinkHeader.parse(response.headers['link']).links
next_link = links.find { |link| link['rel'] == 'next' }
request_url = next_link.href if next_link
if next_link && "#{response.body}" != "[]"
more_data = true
else
more_data = false
end
if response.code == 200
data = JSON.parse(response.body)
data.each do |comments|
CSV.open(output_csv, 'a') do |csv|
csv << [comments['id'], comments['turnitin_data'], comments['submission_comments']]
end
end
else
puts "Something went wrong! Response code was #{response.code}"
end
end
get_comments.run
end
puts "Script done running"
I'm new to this (the ruby code is based on an exercise so I may not fully understand it)- any help/advice would be really appreciated!
EDIT: I should also note that this isn't the total JSON response I'm dealing with - this is just one of ten items that are returned

"submission_comments": [
{
"id": 99999,
}
]
the [] means it is array. {} means it is an object.
So you probably need to do something like this:
json["submission_comments"].first["id"]
or better iterate through it:
ids = json["submission_comments"].map{|comment| comment["id"]}

I'm able to get the variables you need if you can read the JSON file in as text, then use Ruby's JSON.parse(...) method on it. I think the main problem is that JSON uses null but Ruby hashes use nil. You could do a string replace or try something like this (I did not modify your JSON, only put it into a single quoted string):
json_text = '{
"id": 12345,
"body": null,
"url": null,
"grade": "75",
"score": 75,
"submitted_at": "2020-05-02T11:30:53Z",
"assignment_id": 9876,
"user_id": 1111,
"submission_type": "online_upload",
"workflow_state": "graded",
"grade_matches_current_submission": true,
"graded_at": "2017-06-05T08:47:49Z",
"grader_id": 2222,
"attempt": 1,
"cached_due_date": "2020-05-03T15:00:00Z",
"excused": false,
"late_policy_status": null,
"points_deducted": null,
"grading_period_id": null,
"late": false,
"missing": false,
"seconds_late": 0,
"entered_grade": "75",
"entered_score": 75,
"preview_url": "https://etcetc",
"turnitin_data": {
"attachment_33333": {
"status": "scored",
"object_id": "44444444",
"similarity_score": 0,
"web_overlap": 0,
"publication_overlap": 0,
"student_overlap": 0,
"state": "none"
}
},
"attachments": [
{
"id": 33333,
"uuid": "kjsdkjhsdfkhsfd",
"folder_id": 55555,
"display_name": "Submission.pdf",
"filename": "Submission.pdf",
"content-type": "application/pdf",
"url": "https://etcetc",
"size": 2668226,
"created_at": "2020-05-02T11:30:51Z",
"updated_at": "2020-06-06T15:01:46Z",
"unlock_at": null,
"locked": false,
"hidden": false,
"lock_at": null,
"hidden_for_user": false,
"thumbnail_url": null,
"modified_at": "2020-05-02T11:30:51Z",
"mime_class": "pdf",
"media_entry_id": null,
"locked_for_user": false,
"preview_url": "api/etcetc"
}
],
"submission_comments": [
{
"id": 99999,
"comment": "here’s a comment",
"author_id": 1,
"author_name": "Mickey Mouse",
"created_at": "2020-05-15T12:54:08Z",
"edited_at": null,
"avatar_path": "/images/users/1",
"author": {
"id": 1,
"display_name": " Mickey Mouse ",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
},
{
"id": 223344,
"comment": "another comment",
"author_id": 2,
"author_name": "Donald Duck",
"created_at": "2020-06-05T10:48:51Z",
"edited_at": null,
"avatar_path": "/images/users/2",
"author": {
"id": 2,
"display_name": "Donald Duck",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
}
]
}'
Part I added:
ruby_hash = JSON.parse(json_text)
submission_comments = ruby_hash["submission_comments"]
submission_comments.each do |submission_comment|
comment = submission_comment["comment"]
author_id = submission_comment["author_id"]
author_name = submission_comment["author_name"]
puts "Comment: #{comment}, Author ID: #{author_id}, Author Name: #{author_name}\n\n"
end
Terminal Result:
=> Comment: here’s a comment, Author ID: 1, Author Name: Mickey Mouse
=> Comment: another comment, Author ID: 2, Author Name: Donald Duck
Edit: I added a jenky af one-liner version just for fun (presuming the json_text variable above is already initialized)
JSON.parse(json_text)["submission_comments"]
.map{|txt| puts(["comment","author_id","author_name"]
.map{|k| k.instance_eval{"#{upcase}: #{txt[to_s]}"}}.join(', '))}
COMMENT: here’s a comment, AUTHOR_ID: 1, AUTHOR_NAME: Mickey Mouse
COMMENT: another comment, AUTHOR_ID: 2, AUTHOR_NAME: Donald Duck

Related

How to lower levels in json?

I have a component of vuejs and my problem is that when I want a roles.name Roles works, but I don't want all JSON.
A example of JSON:
{
"id_role": 2,
"name": "Prova",
"email": "prova#prova.com",
"email_verified_at": null,
"created_at": "2021-03-01T09:39:42.000000Z",
"updated_at": "2021-03-01T09:39:42.000000Z",
"roles": [
{
"id": 2,
"name": "infomanager",
"guard_name": "web",
"created_at": "2021-03-01T09:39:42.000000Z",
"updated_at": "2021-03-01T09:39:42.000000Z",
"pivot": {
"model_id": 4,
"role_id": 2,
"model_type": "App\\Models\\User"
}
}
]
}
And this is component of vuejs:
export default {
data() {
return {
items: [],
sortBy: '',
sortDesc: false,
output: null,
// Note 'isActive' is left out and will not appear in the rendered table
fields: [
{
key: 'name',
label: 'Nom Usuari',
sortable: true
},
{
key: 'roles.name',
label: 'Nom Rols',
sortable: true
},
{
key: 'actions',
label: 'Accions'
}
],
}
},
My question is how am I down level, roles.name doesn't work.
Thank you so much!!
If I understand your question, you want to replace your roles array-of-objects to an array which holds only roles.name field.
In this case you can use flatMap method from lodash library.
Assume that your JSON is assigned into a variable called rolesJson, it will look like that:
let rolesJson = {
"id_role": 2,
"name": "Prova",
"email": "prova#prova.com",
"email_verified_at": null,
"created_at": "2021-03-01T09:39:42.000000Z",
"updated_at": "2021-03-01T09:39:42.000000Z",
"roles": [
{
"id": 2,
"name": "infomanager",
"guard_name": "web",
"created_at": "2021-03-01T09:39:42.000000Z",
"updated_at": "2021-03-01T09:39:42.000000Z",
"pivot": {
"model_id": 4,
"role_id": 2,
"model_type": "App\\Models\\User"
}
}
]
};
// create a new attribute with the flatted roles array
rolesJson.flatted_roles = _.flatMap(rolesJson.roles, el => {
return el.name;
});
// remove the original roles array
delete rolesJson.roles;

How to parse unnest json data using cypher query language to neo4j database?

In the below json file I want to access "934934507945312256", "934934503604174848",.... and then the keys inside them.
But after using UNWIND clause I am unable to access the data of these keys(quote_count,reply_count,etc.) as these keys("934934507945312256" ,"934934503604174848",...) are randomly generated.
{
"934934507945312256": {
"quote_count": 0,
"reply_count": 0,
"hashtags": null,
"datetime": "2017-11-26 23:58:51",
"date": "2017-11-26",
"like_count": 0,
"verified": "False",
"sentiment": 0,
"author": "Judy💯The Resistance",
"location": "Hollywood, California USA🇺🇸",
"tid": "934934507945312256",
"retweet_count": 0,
"type": "retweet",
"media_list": null,
"quoted_source_id": null,
"url_list": null,
"tweet_text": "RT #kylegriffin1: Reminder: The Senate Judiciary Committee gave Jared Kushner a November 27 deadline to turn over the missing records… ",
"author_profile_image": "https://pbs.twimg.com/profi...",
"author_screen_name": "jgirl66",
"author_id": "23737528",
"lang": "en",
"keywords_processed_list": [
"reminder",
"senate judiciary committee",
"kushner november",
"deadline"
],
"retweet_source_id": "934872065471115264",
"mentions": [
"kylegriffin1"
],
"replyto_source_id": null
},
"934934503604174848": {
"quote_count": 0,
"reply_count": 2,
"hashtags": [
"MissUniverse",
"Thailand"
],
"datetime": "2017-11-26 23:58:50",
"date": "2017-11-26",
"like_count": 38,
"verified": "False",
"sentiment": 0,
"author": "P'Hmee7.5",
"location": "Bangkok, Thailand",
"tid": "934934503604174848",
"retweet_count": 105,
"type": "Tweet",
"media_list": null,
"quoted_source_id": null,
"url_list": null,
"tweet_text": "รอโหวต มรญ #MissUniverse #Thailand",
"author_profile_image": "
Thumbnail
",
"author_screen_name": "Peehmee75",
"author_id": "700720806972624897",
"lang": "th",
"keywords_processed_list": null,
"retweet_source_id": null,
"mentions": null,
"replyto_source_id": null
},
"934934336381636608": {
"quote_count": 0,
"reply_count": 0,
"hashtags": null,
"datetime": "2017-11-26 23:58:10",
"date": "2017-11-26",
"like_count": 0,
"verified": "False",
"sentiment": 0,
"author": "selfresqingprncess",
"location": "Maine, USA",
"tid": "934934336381636608",
"retweet_count": 0,
"type": "retweet",
"media_list": null,
"quoted_source_id": null,
"url_list": null,
"tweet_text": "RT #kylegriffin1: Reminder: The Senate Judiciary Committee gave Jared Kushner a November 27 deadline to turn over the missing records… ",
"author_profile_image": "https://pbs.twimg.com/profi...",
"author_screen_name": "slfresqngprncss",
"author_id": "100536014",
"lang": "en",
"keywords_processed_list": [
"reminder",
"keywords_processed_list": [
"reminder",
"senate judiciary committee",
"kushner november",
"deadline"
],
"retweet_source_id": "934872065471115264",
"mentions": [
"kylegriffin1"
],
"replyto_source_id": null
}
}
There's I have tried :-
query = """
with {json} as data UNWIND data as doc FOREACH( l in doc| MERGE (label1:Label1 {author:l.author}))
"""
But I am getting error:- Cannot merge node using null property value for author.
Your JSON file is malformed.
A JSON string cannot contain control characters (like carriage returns or linefeeds). And your JSON contains an extraneous section (that is probably a copy/paste error):
"keywords_processed_list": [
"reminder",
Furthermore, UNWIND can only be used with lists. You cannot use it to get the properties from a map. Once you have fixed your JSON errors, try the following query (I assume that json is a parameter whose value is your JSON data):
UNWIND KEYS($json) AS k
MERGE(label1:Label1 {author: $json[k].author})

JSON data in Web_custom_request- Vugen

LR script throws warning and fails for the JSON Response.
Below is the script
char *request_json_base;
char *request_json;
web_add_header("Content-Type", "application/json; charset=utf-8");
request_json_base= "{\"GLDefaultId\":0,\"ProjectId\":{ContactProjectId},\"CoaMainId\":10,\"UserId\":{UserId},\"Notes\":\"\",\"PRO_GLDefaultValue\":[{\"GLDefaultValueId\":0,\"GLDefaultId\":0,\"SegmentId\":16,\"Alias\":\"ACT\",\"SegmentType\":\"DETAIL\",\"FunctionTypeId\":0,\"Value\":\"&&&\",\"Mask\":\"&&&\",\"IsRequired\":true,\"LastModified\":null,\"IsCoaRequired\":true},{\"GLDefaultValueId\":0,\"GLDefaultId\":0,\"SegmentId\":17,\"Alias\":\"ST\",\"SegmentType\":\"SET\",\"FunctionTypeId\":0,\"Value\":\"&&\",\"Mask\":\"&&\",\"IsRequired\":false,\"LastModified\":null,\"IsCoaRequired\":false}]}",
request_json = lr_eval_string(request_json_base);
lr_save_string(request_json, "REQUEST_JSON_PARAM");
web_custom_request("PRO_GLDefault",
"URL=https://{URL}/PayrollWebApi/V1/PRO_GLDefault?userId={UserId}",
"Method=POST",
"TargetFrame=",
"Resource=0",
"RecContentType=application/json",
"Referer=",
"Snapshot=t299.inf",
"Mode=HTML",
"EncType=application/json",
"Body={REQUEST_JSON_PARAM}",
LAST);
Below is Replay Log :
Action3_SUNP_ProjectSetup_RatesandSetupInfo.c(81): Warning: The string '"GLDefaultValueId":0,"GLDefaultId":0,"SegmentId":16,"Alias":"ACT","SegmentType":"DETAIL","FunctionTypeId":0,"Value":"&&&","Mask":"&&&","IsRequired":true,"LastModified":null,"IsCoaRequired":true' with parameter delimiters is not a parameter.
Action3_SUNP_ProjectSetup_RatesandSetupInfo.c(81): Warning: The string '"GLDefaultValueId":0,"GLDefaultId":0,"SegmentId":17,"Alias":"ST","SegmentType":"SET","FunctionTypeId":0,"Value":"&&","Mask":"&&","IsRequired":false,"LastModified":null,"IsCoaRequired":false' with parameter delimiters is not a parameter.
Action3_SUNP_ProjectSetup_RatesandSetupInfo.c(83): Notify: Saving Parameter "REQUEST_JSON_PARAM = {"GLDefaultId":0,"ProjectId":1810,"CoaMainId":10,"UserId":67,"Notes":"","PRO_GLDefaultValue":[{"GLDefaultValueId":0,"GLDefaultId":0,"SegmentId":16,"Alias":"ACT","SegmentType":"DETAIL","FunctionTypeId":0,"Value":"&&&","Mask":"&&&","IsRequired":true,"LastModified":null,"IsCoaRequired":true},{"GLDefaultValueId":0,"GLDefaultId":0,"SegmentId":17,"Alias":"ST","SegmentType":"SET","FunctionTypeId":0,"Value":"&&","Mask":"&&","IsRequired":false,"LastModified":null,"IsCoaRequired":false}]}".
Action3_SUNP_ProjectSetup_RatesandSetupInfo.c(85): {"$id":"1","Message":"An error has occurred."}
Below is Body of Original Request call:
"Body={\"GLDefaultId\":0,\"ProjectId\":{ContactProjectId},\"CoaMainId\":10,\"UserId\":{UserId},\"Notes\":\"\",\"PRO_GLDefaultValue\":[{\"GLDefaultValueId\":0,\"GLDefaultId\":0,\"SegmentId\":16,\"Alias\":\"ACT\",\"SegmentType\":\"DETAIL\",\"FunctionTypeId\":0,\"Value\":\"&&&\",\"Mask\":\"&&&\",\"IsRequired\":true,\"LastModified\":null,\"IsCoaRequired\":true},{\"GLDefaultValueId\":0,\"GLDefaultId\":0,\"SegmentId\":17,\"Alias\":\"ST\",\"SegmentType\":\"SET\",\"FunctionTypeId\":0,\"Value\":\"&&\",\"Mask\":\"&&\",\"IsRequired\":false,\"LastModified\":null,\"IsCoaRequired\":false}]}",
LAST);
Below is the Successful Response during the recording:
Request :
{
"GLDefaultId": 0,
"ProjectId": 1806,
"CoaMainId": 10,
"UserId": 2,
"Notes": "",
"PRO_GLDefaultValue": [
{
"GLDefaultValueId": 0,
"GLDefaultId": 0,
"SegmentId": 16,
"Alias": "ACT",
"SegmentType": "DETAIL",
"FunctionTypeId": 0,
"Value": "&&&",
"Mask": "&&&",
"IsRequired": true,
"LastModified": null,
"IsCoaRequired": true
},
{
"GLDefaultValueId": 0,
"GLDefaultId": 0,
"SegmentId": 17,
"Alias": "ST",
"SegmentType": "SET",
"FunctionTypeId": 0,
"Value": "&&",
"Mask": "&&",
"IsRequired": false,
"LastModified": null,
"IsCoaRequired": false
}
]
}
Response:
{
"$id": "1",
"GLDefaultId": 1,
"ProjectId": 1806,
"CoaMainId": 10,
"Notes": "",
"PRO_GLDefaultValue": [
{
"$id": "2",
"GLDefaultValueId": 1,
"GLDefaultId": 1,
"Alias": "ACT",
"FunctionTypeId": 0,
"Value": "&&&",
"SegmentId": 16,
"IsRequired": true,
"ModifiedOn": "7/1/2017 4:48:06 PM",
"ModifiedBy": 2,
"PRO_GLDefault": {
"$ref": "1"
},
"LastModified": null
},
{
"$id": "3",
"GLDefaultValueId": 2,
"GLDefaultId": 1,
"Alias": "ST",
"FunctionTypeId": 0,
"Value": "&&",
"SegmentId": 17,
"IsRequired": false,
"ModifiedOn": "7/1/2017 4:48:06 PM",
"ModifiedBy": 2,
"PRO_GLDefault": {
"$ref": "1"
},
"LastModified": null
}
]
}
Please advise me how to overcome this
Thanks,
Raj
Warning is just that, a warning, not an error, and expected if you have curly braces in your post
What is line 85, where the error is generated?
See these two lines:
request_json_base= "{\"GLDefaultId\":0,\"ProjectId\":{ContactProjectId},\"CoaMainId\":10,\"UserId\":{UserId},\"Notes\":\"\",\"PRO_GLDefaultValue\":[{\"GLDefaultValueId\":0,\"GLDefaultId\":0,\"SegmentId\":16,\"Alias\":\"ACT\",\"SegmentType\":\"DETAIL\",\"FunctionTypeId\":0,\"Value\":\"&&&\",\"Mask\":\"&&&\",\"IsRequired\":true,\"LastModified\":null,\"IsCoaRequired\":true},{\"GLDefaultValueId\":0,\"GLDefaultId\":0,\"SegmentId\":17,\"Alias\":\"ST\",\"SegmentType\":\"SET\",\"FunctionTypeId\":0,\"Value\":\"&&\",\"Mask\":\"&&\",\"IsRequired\":false,\"LastModified\":null,\"IsCoaRequired\":false}]}",
request_json = lr_eval_string(request_json_base);
They are not doing what you think they are doing. You are neither allocating space for this data ( see malloc() in combination with a char * variable), nor are you assigning the value to the variable correctly for the C language (see strcpy() )
Another reference here on Stackoverflow
How to correctly assign a new string value?

parse json output for primary and secondary hosts from replSetGetStatus

I've used pymongo to connect to mongo replica set and print the status of replica set using json dump. I want to parse this output and display "name" and "stateStr" into a list or array for the user to be able to pick a particular host.Here is my json dump output:
{
{
"replSetGetStatus": {
"date": "2016-10-07T14:21:25",
"members": [
{
"_id": 0,
"health": 1.0,
"name": "xxxxxxxxxxx:27017",
"optime": null,
"optimeDate": "2016-10-07T13:50:11",
"self": true,
"state": 1,
"stateStr": "PRIMARY",
"uptime": 32521
},
{
"_id": 1,
"health": 1.0,
"lastHeartbeat": "2016-10-07T14:21:24",
"lastHeartbeatRecv": "2016-10-07T14:21:24",
"name": "xxxxxxxxxxxx:27017",
"optime": null,
"optimeDate": "2016-10-07T13:50:11",
"pingMs": 0,
"state": 2,
"stateStr": "SECONDARY",
"syncingTo": "xxxxxxxxxxxx:27017",
"uptime": 27297
},
{
"_id": 2,
"health": 1.0,
"lastHeartbeat": "2016-10-07T14:21:24",
"lastHeartbeatRecv": "2016-10-07T14:21:24",
"name": "xxxxxxxxxxxxx:27020",
"pingMs": 0,
"state": 7,
"stateStr": "ARBITER",
"uptime": 32517
}
],
"myState": 1,
"ok": 1.0,
"set": "replica1"
}
}
Please try below Javascript code. It worked for me.
use admin;
var result = rs.status();
var length = result.members.length;
for (var i=0;i<length;i++){
print ("Server Name-" +result.members[i].name);
print ("Server State-" +result.members[i].stateStr);
}

Serialize the response from backend to store ember store

My response from backend is not in form which ember store. I am not able to serialize the response.
response.json
[{
"pk": 127,
"url": "http://example.com/api/galleries/127/",
"gallery_name": "Faces",
"thumbnail_url": "https://example.cloud.net/galleryThumbs/2656a05c-4ec7-3eea-8c5e-d8019454d443.jpg",
"time": "1 month ago",
"description": "Created by user",
"is_following": true,
"feedPhotos": [{
"pk": 624,
"url": "http://example.com/api/photos/624/",
"profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
"userName": "Nabeela",
"userKarma": 915,
"caption": "Old woman spinning her 'chhos-khor' ...a rotation of which is equivalent to the recitation of a mantra.",
"numComments": 0,
"owner": "http://example.com/api/users/44/",
"time": "1 month ago",
"photo_url": "https://example.cloud.net/photos/9cbd6423-3bc5-36e0-b8b4-d725efb3249a.jpg",
"comments_url": "http://example.com/api/photos/624/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/1362/fivers/",
"fivers_pk": 1362,
"fullphoto_url": "http://example.com/api/photogalleries/1362/photo/",
"fullphoto_pk": 1362,
"is_fived": true,
"hiFiveKarma": 1,
"owner_pk": 44,
"userFirstName": "Nabeela",
"is_bookmarked": false
}, {
"pk": 574,
"url": "http://example.com/api/photos/574/",
"profilePic": "https://example.cloud.net/userDPs/b6f69e4e-980d-3cc3-8b3e-3eb1a7f21350.jpg",
"userName": "Rohini",
"userKarma": 194,
"caption": "Life # Myanmar!",
"numComments": 0,
"owner": "http://example.com/api/users/45/",
"time": "2 months ago",
"photo_url": "https://example.cloud.net/photos/eeae72d5-d6af-391e-a218-b442c0c7e34e.jpg",
"comments_url": "http://example.com/api/photos/574/comments/",
"numFives": 2,
"fivers_url": "http://example.com/api/photogalleries/1303/fivers/",
"fivers_pk": 1303,
"fullphoto_url": "http://example.com/api/photogalleries/1303/photo/",
"fullphoto_pk": 1303,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 45,
"userFirstName": "Rohini",
"is_bookmarked": false
}
]
}, {
"pk": 65,
"url": "http://example.com/api/galleries/65/",
"gallery_name": "Royal",
"thumbnail_url": "https://example.cloud.net/galleryThumbs/d8a900af-1f1d-3977-8cc8-b8bb36e32be5.jpg",
"time": "2 months ago",
"description": "This is a gallery about Royal",
"is_following": false,
"feedPhotos": [{
"pk": 347,
"url": "http://example.com/api/photos/347/",
"profilePic": "https://example.cloud.net/userDPs/50906ce2-394d-39c8-9261-8cf78e3611c2.jpg",
"userName": "Nabeela",
"userKarma": 915,
"caption": "I cannot forget the name of this palace - Moti Mahal (translation: Pearl Palace). Indescribably beautiful, ainnit! at Mehrangarh fort, Jodhp",
"numComments": 0,
"owner": "http://example.com/api/users/44/",
"time": "2 months ago",
"photo_url": "https://example.cloud.net/photos/958ed406-708e-3f01-a2f4-9467cd709fdd.jpg",
"comments_url": "http://example.com/api/photos/347/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/759/fivers/",
"fivers_pk": 759,
"fullphoto_url": "http://example.com/api/photogalleries/759/photo/",
"fullphoto_pk": 759,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 44,
"userFirstName": "Nabeela",
"is_bookmarked": false
}, {
"pk": 593,
"url": "http://example.com/api/photos/593/",
"profilePic": "https://example.cloud.net/userDPs/95ac6974-f7df-338c-ab84-99fa1df7514c.jpg",
"userName": "Vikanshu",
"userKarma": 932,
"caption": "Marvelous architecture!! in Florence, Italy",
"numComments": 0,
"owner": "http://example.com/api/users/48/",
"time": "1 month ago",
"photo_url": "https://example.cloud.net/photos/7a86eb37-6c68-3d6c-b6cf-2e3b74d330dd.jpg",
"comments_url": "http://example.com/api/photos/593/comments/",
"numFives": 4,
"fivers_url": "http://example.com/api/photogalleries/1363/fivers/",
"fivers_pk": 1363,
"fullphoto_url": "http://example.com/api/photogalleries/1363/photo/",
"fullphoto_pk": 1363,
"is_fived": false,
"hiFiveKarma": 0,
"owner_pk": 48,
"userFirstName": "Vikanshu",
"is_bookmarked": false
}]
}]
How do I serialize this using JSONPISerailizer or any other serializer in ember-cli so that it gets stored in ember store
Reference jsonapi.org
++++Top Level:
Root:
A JSON object must be root of every JSON API request response.
A document must contain at least one top-level members:
1. data: documents "primary data"
2. errors: an array of error objects (id,status,code,title....)
3. meta: a meta object that contains non-standard meta-information (copyright,author...)
member data and errors must not co-exist together.
"data"{}
+++++Resource Objects
1. A resource object MUST contain atleast following top-level member
*id
*type
```
//structure-1
//for galleries
{
"data": {
"type": "galleries",
"id": "1"
}
}
//for photos
{
"data": {
"type": "photos",
"id": "1"
}
}
```
In addition, a resource object may contain any of these top-level members
*attributes
*relationship
*links
*meta
//added attributes first
```
//structure-2
//for galleries
{
"data": {
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
}
}
}
//for photos
{
"data": {
"type": "photos",
"id": "1",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}
}
```
//Adding relationship
Relationship object must contain atleast one of the following
*links (containing atleast one of "self" or "related" resource link
*data
*meta
//link in relationship (minimum one required from link,data,meta).
//
```
//structure-3
//for galleries
{
"data":[{ //Array(square bracket as adding relationship one more item to data
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
}]
}
}
```
//data in relationship
```
//structure-4
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
}]
}
}
```
//Adding related resource "included"
```
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
}],
"included":[{
"type": "photos",
"id": "77",
"attributes":{
userName: "Nabeela",
userKarma: 915
},
{
"type": "photos",
"id": "78",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}]
}
}
```
For collections. I am not confident but try this
Now for collection of galleries.
//for galleries
{
"data": [{
"type": "galleries",
"id": "1",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "77"
}
},{
"type": "galleries",
"id": "2",
"attributes": {
"galleryName": "Faces"
"thumbnailUrl:"https://example.cloud.net/galleryThumbs/2656a05c-4ec7.jpg",
"description": "Created by user",
},
"relationships":{ //This has all your photo stuff
"links":{
"self": "https://example.cloud.net/photos/9cbd6423.jpg //"photo_url" in your payload
},
"data": { //picked it up from structure-1
"type": "photos",
"id": "79"
}
}],
"included":[{
"type": "photos",
"id": "77",
"attributes":{
userName: "Nabeela",
userKarma: 915
},{
"type": "photos",
"id": "78",
"attributes":{
userName: "Nabeela",
userKarma: 915
},{
"type": "photos",
"id": "79",
"attributes":{
userName: "Nabeela",
userKarma: 915
}
}]
}
}
============Implementation part =================================
JSONSerializer normalization process follows these steps
*normalizeResponse : entry method.
*normalizeCreateRecordResponse : a normalizeResponse for specific operation.
*normalizeSingleResponse|normalizeArrayResponse:
- for methods like createRecord. we expect a single record back.
- for methods like findAll we expect multiple records back.
+normalize =
normalizeArray iterates and calls normalize for each of it's records
normalizeSingle call its once.
+extractID | extractAttributes | extractRelationships
= normalize delegates to these method to turn record payload into jsonAPI format
Starting with normalizeResponse method. If you open and see normalizeResponse method
in json-serializer
link normalizeResponse: https://github.com/emberjs/data/blob/v2.2.1/packages/ember-
data/lib/serializers/json-serializer.js#L192
you with find a switch case switch(requestType). If requestType if
"findRecord" then "normalizeFindRecordResponse" is called
"queryRecord" then "normalizeQueryRecordResponse" is called
"findAll" then "normalizeFindAllResponse" is called
...so on and so forth.
if you notice the parameter passed to all the methods are same as that of normalize
(...arguments) :)
**Lets start for findAll
i.e normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse
as normalizeFindAllResponse method has only one line that call
normalizeArrayResponse.
normalizeFindAllResponse
normalizeResponse -> normalizeFindAllResponse -> normalizeArrayResponse ->
_normalizeResponse{ extractMeta,normalize }
extractMeta [extract meta information like pagination and stuff ]
if single: normalize []
example of normalize method in emberjs docs
```
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
"normalizeArrayResponse calls `return this._normalizeResponse
(store,primaryModelClass,payload,id,requestType,false).
so isSingle is false for _normalizeResponse method. so we will have to push all the
related records of included array
in our case the photos which is done by below snippet from "_normalizeRespose"
method.
_normalizeResponse
```
else{
documentHash.data = payload.map((item) => {
let { data, included } = this.normalize(primaryModelClass,item);
if(included){
documentHash.included.push(...included);
}
return data;
});
return documentHash;
}
```
Things are still unclear in the context of our JSON reponse from server
but atleast we know the flow now.
Lets try to apply it for findAll ( as per the flow above).
run "ember g serializer application" //assuming you are using ember-cli and you
intend to make this serializer generic for application.
As of now I have no information how and when normalizeResponse is called. :(
I just scanned through and guess on recieving data from server the store calls
normalizeResponseHelpers which in turn calls normalizeResponse.
In any case "normalizeResponse" is going to send payload and other necessar
information to normalizeFindAllResponse(...arguments) which in turn will call
normalizeArrayResponse(...arguments) which in turn will call "_normalizeRespone".
Here is where we need to take action
for extraMeta and normalize.
+extraMeta
I am not sure if there is any meta information in you json response.
in case there is you can refer to the example mentioned in docs
extractMeta
So I guess you can directly user the normalize method from example in your application ;).
please try and check. Since i am learning ember myself I cannot guarantee it will work but it should. the lonngggg explation is my thought while i was learning the problem/solution
//app/serializers/application.js
+normalize
```
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
normalize: function(typeClass, hash) {
var fields = Ember.get(typeClass, 'fields');
fields.forEach(function(field) {
var payloadField = Ember.String.underscore(field);
if (field === payloadField) { return; }
hash[field] = hash[payloadField];
delete hash[payloadField];
});
return this._super.apply(this, arguments);
}
});
```
The primary key in the JSON from server is pk. You will have to mention that too
http://emberjs.com/api/data/classes/DS.JSONSerializer.html#property_primaryKey
app/serializers/application.js
import DS from 'ember-data';
export default DS.JSONSerializer.extend({
primaryKey: 'pk'
});