Home > Software design >  How do I call a multiple layer deep Object or a Value of a JSON database?
How do I call a multiple layer deep Object or a Value of a JSON database?

Time:11-09

I created a Json Server Database like this:

"Time":
  [
    {
     "id":1,
     "name":
     [
      {
       "id":1,
       "checkin":
       [
        {
         "id":1,
         "date":"123",
         "time":"123"
        },
        {
         "id":2,
         "date":"123",
         "time":"123"
        }
       ]
      },
      {
       "id":2,
       "checkout":
       [
        {
         "id":1,
         "date":"123",
         "time":"123"
        }
       ]
      }
     ]
    }
   ]

I don't want to get the entire Database and go through it. I just want to tell the Database where exactly my Object is and have it returned.

How would I call the call for example the first Check-in Object?

I use the Angular HttpClient like this:

this.http.get(endpoint, JSON.stringify(time), this.httpOptions))

So I need the Exact Endpoint in a format like: endpoint/id/id or similar

I imagined it like this: endpoint/time/1/1
With output:

[
 {
  "id":1,
  "date":"123",
  "time":"123"
 }
]

If this is not possible please tell me anyways.

PS: The question from this thread is essentially the same as mine. Also the JSON documentation doesn't real help either, it just says you need custom routes for multilayer JSON strings but not how to implement these routes.

CodePudding user response:

I'm not sure if I understand correctly where you are returning the data from. If you meant json-server, just look at the documentation (here) and then you could use an endpoint like "/posts?Id=2" However, if you mean your own API, which does not have an endpoint that returns one record, e.g. by its ID, the only convenient solution is to create a service that will map the result from the server and return the desired value. You can do all this in one place, but for clearer code, I recommend dividing it into:

  • service that will download data from the server
  • service that will map the data on the basis of a given parameter
  • component that will display the data

Below is a working example on Stackblitz. example

Note that in the app-component I pass the ID 32 to the method from the mapping service as the parameter. The mapping service then calls a method that sends the request for all the data.

The important thing is that all data is returned to the application, not just one record. If the API you are using does not provide such an endpoint, it is not possible to return only one record.

CodePudding user response:

Apparently a request like I wanted to call is still not possible. The only way to come close is to fake it with custom Routes and flattening the JSON structure like in this old thread.

  • Related