Are JSON nested objects necessary? - json

I have a question about the way JSON is written. Which is better in terms of usability? I am trying to use a single JSON file for decoding in PHP and Swift, and was wondering which would be the better way for the JSON to be written. Nested objects or no nested objects, essentially.
Option 1
{
"title": "Test",
"image": "image",
"imageCard": "imae2",
"count": 20,
"section": "personal",
"description": "Description",
"color": "#F17B08",
"content": {
"video": true,
"text": true,
"updated": false
},
"homepage": {
"featured": false,
"popular": false,
"new": false
},
"levels": "7-12"
}
]
Option 2
[
{
"title": "Test",
"image": "image",
"imageCard": "imae2",
"count": 20,
"section": "personal",
"description": "Description",
"color": "#F17B08",
"video": true,
"text": true,
"updated": false,
"featured": false,
"popular": false,
"new": false,
"levels": "7-12"
}
]
Thanks!

A JSON structure is often bound to be mapped to an object-oriented class. The closer the JSON structure is from the Model of your program (all the classes, and how each has one or many relationships to others), the easier it will be to deserialize the response from the API.
Now, JSON nesting is necessary just as much as you make associations, compositions and aggregations with your classes.
Let's say you have a Student that has a name, an unique ID and a Teacher which gives many Courses
Having a nested JSON such as:
[
{
"Name":"John Doe",
"ID":"948AFF",
"Teacher":{
"John Nash",
"Classes":[
{...},
{...},
{...}
]
}
},
{
"Name":"William Smooth",
"ID":"123LMLG",
"Teacher":{
"Ulrich Stokes",
"Classes":[
{...},
{...},
{...}
]
}
}
]
Is an intuitive, clean, flexible way to structure the JSON. Because it maps easily to your model. Each element of the array is an instance of a Student which has an instance of Teacher, which has a list of Courses.
Whereas if you had a flat structure like you suggest :
[
{
"Name":"John Doe",
"ID":"948AFF",
"TeacherName":"John Nash",
"ClassesOfTheTeacher":[
{...},
{...},
{...}
]
},
{
"Name":"William Smooth",
"ID":"123LMLG",
"TeacherName":"Ulrich Stokes",
"ClassesOfTheTeacher":[
{...},
{...},
{...}
]
}
]
Forces you to systematically map each field to the attribute of one of your classes. It doesn't stick easily to your model, you have to make some manipulations to map this to your model.
Furthermore, what if suddenly you wanted to have .. 3 Teachers for each student ? Would you end up with TeacherName1, TeacherName2, TeacherName3, and ClassesOfTheTeacher1, ClassesOfTheTeacher2, etc. ? Probably not.
Nested JSON is necessary if you have association/composition/aggregation in your classes.

Related

replace "key" name in whole JSON python for bulk data in efficient way

Actually i am pushing data to other system but before pushing i have to change the "key" in the whole JSON. JSON may contain 200 or 10000 or 250000 data.
sample JSON:
{
"insert": "table",
"contacts": [
{
"testName": "testname",
"ContactID": 212121
},
{
"testName": "testname",
"ContactID": 2146354564
},
{
"testName": "testname",
"ContactID": 12312
},
{
"testName": "testname",
"ContactID": 211221
},
{
"testName": "testname",
"ContactID": 10218550
}
]
}
I need to change contacts array Keys. These contacts may be in bulk. So i need to work with this efficiently with minimal complexity.
The above JSON to be converted as below
{
"insert": "table",
"contacts": [
{
"name": "testname",
"phone": 212121
},
{
"name": "testname",
"phone": 2146354564
},
{
"name": "testname",
"phone": 12312
},
{
"name": "testname",
"phone": 211221
},
{
"name": "testname",
"phone": 10218550
}
]
}
here is my code trying by loop
ini_dict = request.data
contact_data = ini_dict['contacts']
for i in contact_data:
i['name'] = i.pop('testName')
print(contact_data)
Please suggest me how can i change the key names efficiently for bulk data. i mean for 50000 lists in contacts. "for loop" will be leading a performance issue. So please let me know the efficient way to achieve this
I dont know how fast you need it to be nor how you are choosing to store your json. One simple solution is just store it as a string and then replace all the instances of your attributes.
# Something like this using a jsonstring
jsonstring.replace("'testName':", "'name':")
jsonstring.replace("'ContactId':", "'phone':")
If you want to do this in bulk you, may need to create some batch process to be able to fetch multiple existing records and make changes at once. I have done this before with the java equivalent of https://pypi.org/project/JayDeBeApi/ but, that was more for modifying existing records in a database.

Google json style guide: How to send single item response?

There is an items node in the specifications which says it is for an array of items, like paging items, youtube video list
What if I have GET request on a single item, how should the response be formatted ?
Just to one item in the array?
items:[item]
https://google.github.io/styleguide/jsoncstyleguide.xml
I don't think #tanmay_vijay's answer is correct or nuanced enough as it seems that single item responses are in arrays in the YouTube example in the docs.
{
"apiVersion": "2.0",
"data": {
"updated": "2010-02-04T19:29:54.001Z",
"totalItems": 6741,
"startIndex": 1,
"itemsPerPage": 1,
"items": [
{
"id": "BGODurRfVv4",
"uploaded": "2009-11-17T20:10:06.000Z",
"updated": "2010-02-04T06:25:57.000Z",
"uploader": "docchat",
"category": "Animals",
"title": "From service dog to SURFice dog",
"description": "Surf dog Ricochets inspirational video ...",
"tags": [
"Surf dog",
"dog surfing",
"dog",
"golden retriever",
],
"thumbnail": {
"default": "https://i.ytimg.com/vi/BGODurRfVv4/default.jpg",
"hqDefault": "https://i.ytimg.com/vi/BGODurRfVv4/hqdefault.jpg"
},
"player": {
"default": "https://www.youtube.com/watch?v=BGODurRfVv4&feature=youtube_gdata",
"mobile": "https://m.youtube.com/details?v=BGODurRfVv4"
},
"content": {
"1": "rtsp://v5.cache6.c.youtube.com/CiILENy73wIaGQn-Vl-0uoNjBBMYDSANFEgGUgZ2aWRlb3MM/0/0/0/video.3gp",
"5": "https://www.youtube.com/v/BGODurRfVv4?f=videos&app=youtube_gdata",
"6": "rtsp://v7.cache7.c.youtube.com/CiILENy73wIaGQn-Vl-0uoNjBBMYESARFEgGUgZ2aWRlb3MM/0/0/0/video.3gp"
},
"duration": 315,
"rating": 4.96,
"ratingCount": 2043,
"viewCount": 1781691,
"favoriteCount": 3363,
"commentCount": 1007,
"commentsAllowed": true
}
]
}
}
It could however be that it depends on the resource being targeted from the request. This is the way it is in the competing JSONAPI standard.
From JSONAPI standard:
A logical collection of resources MUST be represented as an array, even if it only contains one item or is empty.
You don't need to have items field for showing single item. If you're sure your API is always going to return single object, you can return it as data itself.
{
"data": {
"kind": "user",
"fields": "author,id",
"id": "bart",
"author": "Bart"
}
}
Fields such as data.kind data.fields data.etag data.id data.lang data.updated data.deleted can still be used here.
Source for snippet docs

Deeply nested JSON documents in Apache Solr

I have a deeply nested document(pseudo structure as shown below):
[{
"id": "1",
"company_id": "1",
"company_name": "company_1",
"departments":[{
"dep1" : [{
"id" : 40,
"name" : xyz
},
{
"id" : 41,
"name" : xyr
}],
"dep2": [{
}]
}]
"employeePrograms" :[{
}]
}]
How can I index these type of documents in Apache Solr?
Documentation gives the idea of immediate child documents alone.
Unfortunatelly i'm don't have huge experience with this technology, but want to help. Here is some official documentation, that might be useful: oficial doc
more specific
If you have some uncommon issue, tell about it, maybe any error, or whatever.. I would try my best to help)
Upd1 :
Solr can only maintain a 'flat' representation of the data. What you weretrying to do is not really possible. There are a number of workarounds, such as using dynamic fields and using a solr join to link multiple data sets.
Speking about a deep nesting ? I've found such an example of work around.
If you had something like that:
"docs": [
{
"name": "Product Name",
"categories": [
{
"name": "Category 1",
"priority": 8
},
{
"name": "Category 2",
"priority": 6
}
...
]
},
You have to modify it like that to make it not deeply nested :
"docs": [
{
name: "Sample Product"
categories: [
{
priority_category: "9_Category 1",
},
{
priority_category: "5_Category 2",
}
...
]
},
So, you've done something similar, check if there are any errors anywhere

JSON is it best practice to give each element in an array an id attribute?

Is it best practice in JSON to give objects in an array an id similar to below?. Im trying to decide on a JSON format for a restful service im implementing and decide include it or not... If it is to be modified by CRUD operations is it a good idea?
{
"tables": [
{
"id": 1,
"tablename": "Table1",
"columns": [
{
"name": "Col1",
"data": "-5767703747778052096"
},
{
"name": "Col2",
"data": "-5803732544797016064"
}
]
},
{
"id": 2,
"tablename": "Table2",
"columns": [
{
"name": "Col1",
"data": "-333333"
},
{
"name": "Col2",
"data": "-44444"
}
]
}
]
}
Client-Generated IDs
A server MAY accept a client-generated ID along with a request to
create a resource. An ID MUST be specified with an "id" key, the value
of which MUST be a universally unique identifier. The client SHOULD
use a properly generated and formatted UUID as described in RFC 4122
[RFC4122].
jsonapi.org

How to merge JPA entity structure on a POST/PUT RESTful webapp

I am starting to implement a REST layer to an existing JSF-webapp (using RESTEasy, with a Jettison provider). Since tutorials for Java REST layers are quite basic (simple objects) I am facing the question how existing JPA entity relations can be easily exposed to/consumed from the client. A simple "/user" REST-method already gives me successfully the output below, which is a good start. But my main question is - how to deal with this kind of structures. Is it common to use such structures through REST?
I don't want to expose all details or the whole entity-tree, wether it is because of irrelevance, saving traffic or security issues. Using #XmlTransient works fine for the #Procudes, but merging these entities on a #POST/#PUT all #XmlTransient properties are merged to NULL. What is right way of doing that?
Since #XMLTransient is a global and permanent setting - what is the right approach to dynamically decide which depth of entity-tree I want to expose?
thanks
Example JSON of User-entity:
{
"user": {
"id": ..,
"uuid": "1521ccad69ba4579bbe49e75181fefc1",
"image": "",
"contact": {
"id": ..,
"uuid": "8eb429dcca994834ae5c8cf07cba62a2",
"cellphone": "",
"city": "",
"country": "",
"email": "mail#foo.bar",
"fax": "",
"phone": 555,
...
},
"name": "...",
"account": {
"id": ...,
"uuid": "80b331f9e6644449bb3600b0e5145253",
"confirmed": true,
"profile": {
"id": ...,
"uuid": "e172bdcafe2645d7975852ca5685c98c",
"locale": "en",
"notifyMessage": false,
"notifyNews": true,
"notifyTask": true,
"timeZone": "Europe/Berlin"
},
"roleProfiles": {
"id": ..,
"uuid": "f1713758f3f2416faed3e68350f2d759",
"active": true,
"assemblies": [
{
"id": ..,
"uuid": "13d72449833a4eb0b5b4f62c729ee44f",
"image": "",
"commercialRegisters": [
123,
456
],
"contact": {
"id": ...,
"uuid": "bef3802297344e3c8c3619b6c91c345a",
"city": "",
"country": "",
...
},
"thumbnail": ""
},
{
...
}
],
},
"userName": "..."
},
"displayName": "...",
"firstName": "Foo",
"lastName": "Bar",
"salutation": "",
"title": ""
}
}
Hi references in your Java classes should be serialized to JSON as links and not as values.
This is how Spring REST does it.
The good thing is : That way you have a kind of lazy loading
The bad thing is that the client needs additional requests to get the values of the references.
I developed a complete solution for that, but that was a hard piece of work.
The client (in javascript) creates proxies for those references and resolves them on demand.
I have a demo of that at demo.appdriver.com
In the upper right corner you see a link 'REST API' click it and you can see the REST API of a rather complex domain model.
Now you can start to click on the user interface , create, change, delete etc.
and have a look at the traffic between client and server.
Hope it helps !