Customise ActiveRecord JSON Response without a Serializer - json

I'm rendering some JSON using sinatra/contrib. I want to customise my JSON response not to include "teacher_id" in the associated record. How do I do this?
get '/teachers' do
json Teacher.includes(:courses).all.as_json(include: :courses)
end
Will render:
{
"id": 1,
"name": "Dave",
"age": 27,
"specialism": "Ruby",
"courses": [
{
"id": 1,
"title": "WDI",
"teacher_id": 1
}
]
}
I would like to remove, teacher_id:
{
"id": 1,
"name": "Dave",
"age": 27,
"specialism": "Ruby",
"courses": [
{
"id": 1,
"title": "WDI"
}
]
}
I can use the except: syntax to remove id, name, age and specialism. How can I remove the associated property?
Thanks in advance.

You can use the :except option for associations like this:
Teacher.includes(:courses).all
.as_json(include: { courses: { except: :teacher_id } })

Related

In AngularJS, Adding field to Array from another json file, possible callback issue

AngularJS Service:
Get json sub-record field for import into current open array record.
I have one json file with "services" in it (id, name) services.json,
I need to forEach through them, but as I am in each service I need to open sub-record(welding.json) and grab a field(title) and add it to the current record.
NOTE: My project is a CLI type.
services.json
[
{
"id": 1,
"name": "welding"
},
{
"id": 2,
"name": "carpentry"
},
{
"id": 3,
"name": "mechanic"
}
]
= Sub-Records =
welding.json
{
"category": "labor",
"title": "Arc Welding",
"description": "",
"experience": "20+ Years",
"details": ""
}
Expectation:
{
"id": 1,
"name": "welding",
"title": "Arc Welding"
}
Try this
angular.forEach($scope.services, function (value, key) {
if(value.name == 'welding'){
$http.get('welding.json').then(function (response) {
$scope.welding = response;
})
$scope.services.title=$scope.welding.title;
}});

How to Append JSON Object in already created object in mysql json document

My object is
{
"name":"Testing",
"id": "hcig_3fe7cb00-e936-11e6-af69-a748c8cc89ad",
"belongsTo": {
"id": "69616d26-c3bb-405c-8c84-c51c091524b2",
"name": "test"
},
"locatedAt": {
"id": "49616d26-c3bb-405c-8c84-c51c091524b2",
"name":"Test"
} }
I want to merge one more object like
"obj":[{
"a": 123
}}
With the help of JSON_MERGE in mysql document store i am able to add object.
But it looks likes
{
"name":"Tester",
"id": "hcig_3fe7cb00-e936-11e6-af69-a748c8cc89ad",
"belongsTo": {
"id": "69616d26-c3bb-405c-8c84-c51c091524b2",
"name": "test"
},
"locatedAt": {
"id": "49616d26-c3bb-405c-8c84-c51c091524b2",
"name":"Test"
},{
"obj":[{
"a": 123
}]
}}
I want my object to be as
{
"name": "Tester",
"id": "hcig_3fe7cb00-e936-11e6-af69-a748c8cc89ad",
"belongsTo": {
"id": "69616d26-c3bb-405c-8c84-c51c091524b2",
"name": "test"
},
"locatedAt": {
"id": "49616d26-c3bb-405c-8c84-c51c091524b2",
"name": "Test"
},
"obj": [{
"a": 123
}]}
Any idea on how to add object as above manner using JSON Functions in mysql ??
Use lodash for a recursive deep copy - https://lodash.com/
lodash.merge(targetObj, sourceObj);
Or if you have programmatic access:
targetObj.obj = sourceObj;

Remove pivote attribute from JSON response in Laravel 5.2

I'm using many to many relationships using pivot table. But the problem is when I'm returning json response, the json also contains the pivot attribute as shown below:
{
"id": 2,
"job_title": "et",
"job_description": "Iusto provident.",
"job_industry": "Braun, Jast and Quigley",
"job_location": "Christiansenland",
"job_experience": 7,
"employment_type": "full",
"recruiter_id": 9,
"status": 1,
"posted_date": "2016-02-02 07:55:28",
"skills": [
{
"id": 1,
"value": "molestiae",
"pivot": {
"job_id": 2,
"skill_id": 1
}
}
]
}
What I want is something like this:
{
"id": 2,
"job_title": "et",
"job_description": "Iusto provident.",
"job_industry": "Braun, Jast and Quigley",
"job_location": "Christiansenland",
"job_experience": 7,
"employment_type": "full",
"recruiter_id": 9,
"status": 1,
"posted_date": "2016-02-02 07:55:28",
"skills": [
{
"id": 1,
"value": "molestiae",
}
]
}
I have tried various solutions from the stackoverflow questions, but none of them seem to work. I'm new to Laravel. If you guys need more info on the model,I can post it. Please help.
Go to your Skill model and set:
protected $visible = ['id', 'value'];

Django + rest-framework: serialize arbitrary query

I have three classes representing different sections in my models: SectionA, SectionB, SectionC.
Each of these sections have associated a set of items (class Item in my model).
I would like to get a json similar to this:
{
"sectionA": [
{
"id": 1,
"picture": "car_pic1",
"category": "cat1"
},
{
"id": 3,
"picture": "car_pic1",
"category": "cat2"
},
{
"id": 5,
"picture": "car_pic1",
"category": "cat3"
}
],
"sectionB": [
{
"id": 2,
"picture": "car_pic1",
"category": "cat8"
},
{
"id": 4,
"picture": "car_pic1",
"category": "cat9"
},
{
"id": 7,
"picture": "car_pic1",
"category": "cat10"
},
],
"sectionC": [
{
"id": 9,
"picture": "car_pic1",
"category": "cat9"
},
{
"id": 10,
"picture": "car_pic1",
"category": "cat9"
},
{
"id": 11,
"picture": "car_pic1",
"category": "cat10"
},
]
}
This json displays any three items associated to each section.
I would like to know how can I implement this using rest-framework. Basically I need to perform a query retrieving the three items for each section (since this json is not associated to a model object) and serialize all this into the json. I'm not sure where or how to perform these queries and I didn't have any success so far.
Finally I did it slightly different. My view just creates a dictionary with each section and its associated items:
class SectionList(APIView):
"""
List three objects for each section.
"""
def generate_data(self):
#query to get the items of each section
list_items = []
list_items.append({"section" : "sectionA", "items" : secA_items})
list_items.append({"section" : "sectionB", "items" : secB_items})
list_items.append({"section" : "sectionC", "items" : secC_items})
return list_items;
def get(self, request, format=None):
section_list = self.generate_data()
serializer = SectionSerializer(section_list)
return Response(serializer.data)
And this is the serializer I used:
class SectionSerializer(serializers.Serializer):
section = serializers.CharField(max_length=200)
items = ItemSerializer(many=True)

What is the correct format in JSON, should I quote names also?

I am writing a JSON file, but I am not sure about which of the following formats is the correct one?
Quoting variable names and all string values
{
"class": {
"number": 2,
"student": {
"name": "Tom",
"age": 1
},
"student": {
"name": "May",
"age": 2
}
}
}
or
Quoting only string values
{
class: {
number: 2,
student: {
name: "Tom",
age: 1
},
student:
{
name: "May",
age: 2
}
}
}
The first is valid, if you're unaware you can validate your JSON output online pretty easily here: http://www.jsonlint.com/
JSON requires the quotes. See http://json.org for the specifications.
In particular, the string production is:
string
'"' characters '"'
Old question, but the OP's JSON (first construction) may have the proper syntax, but it's going to cause trouble because it repeats the key student.
import simplejson
data = '''{
"class": {
"number": 2,
"student": {
"name": "Tom",
"age": 1
},
"student": {
"name": "May",
"age": 2
}
}
}'''
data_in = simplejson.loads(data)
print(data_in)
Yields: {'class': {'number': 2, 'student': {'age': 2, 'name': 'May'}}}
Where unique keys student_1 and student_2:
import simplejson
data = '''{
"class": {
"number": 2,
"student_1": {
"name": "Tom",
"age": 1
},
"student_2": {
"name": "May",
"age": 2
}
}
}'''
data_in = simplejson.loads(data)
print(data_in)
Yields: {'class': {'student_1': {'age': 1, 'name': 'Tom'}, 'number': 2, 'student_2': {'age': 2, 'name': 'May'}}}
UPDATE:
Agree with #Tomas Hesse that an array is better form. It would look like this:
import simplejson
data = '''{
"class": {
"number": 2,
"students" : [
{ "name" : "Tom", "age" : 1 },
{ "name" : "May", "age" : 2 }
]
}
}'''
data_in = simplejson.loads(data)
print(data_in)