Explore a JSON array within another JSON array

Here is a JSON format that I have:

{
   "Project 
      [id=1, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd ]"
    :
 [
  {"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26"},
  {"id":2,"title":"sss ","description":"sss","dateFin":"2017-01-26"}
 ]
}

Generated from :

return new ObjectMapper.write(Map<Project,List<Task>> projectTasks = new LinkedMultiValueMap<>()) ;

UPDATE: Here is the actual response :

{"Project [id=1, name=qsdsqd, type=null, done=false, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd, client=qsd, showable=true]":
[{"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26","dateDebut":"2017-01-14","period":null,"done":false,"status":"Actif","priority":"Normal"},
{"id":2,"title":"task 2 ","description":"qsdqsd","dateFin":"2017-01-26","dateDebut":"2017-01-14","period":null,"done":false,"status":"Actif","priority":"Normal"}]}

How do I access and read the list of tasks on the client side?

Answer №1

First and foremost, the JSON you provided is invalid. Have you double-checked if there should be a line break between the word Project and [id...]? A correctly formatted JSON would look like this:

{
   "Project [id=1, dateDebut=2017-01-13, dateFin=2017-01-18, description=qsd, sponsor=qsd, ]":
 [
  {"id":1,"title":"qsd ","description":"qsdqsd","dateFin":"2017-01-26"},
  {"id":2,"title":"sss ","description":"sss","dateFin":"2017-01-26"}
 ]
}

Although it's possible to use object keys like that, it might not be the most convenient way to retrieve data.

If changing your data schema is not an option (or something you prefer not to do), you can iterate through the Object using the

Object.keys(obj).forEach ( (key) => {
   console.log('key: ' + key);
   console.log('value: ' + obj[key]);

   /* You can iterate through your values (tasks) here */
   obj[key].forEach( (task) => {
      console.log('task1: ', task);
   });

});  //where obj represents your json

Alternatively, you can access the first object property with:

obj[Object.keys(obj)[0]]; //where obj represents your json

UPDATE @André Dion noted that forEach is more appropriate for iteration rather than map. Also, make sure that your response has been parsed from the server (either by yourself or with a library like jQuery). If not, you should utilize JSON.parse(response); to extract the object.

Answer №2

Feel free to give this a shot: Let's assume that the response mentioned above is stored in a variable called 'response'.

for(var item in response) { // This will loop through each item in the response
    for(var i=0; i<item.length; i++) { // This will go through the array of tasks for each item
         console.log("Task: " + item[i]);
         console.log(item[i]["id"]); // Accessing the id of each task, and you can do the same for other attributes
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can the syntax of a JSON file be verified in Unix?

How can I verify the syntax of a JSON file in Unix and then automatically move any invalid files into an error folder? Thank you, Kavin ...

Having trouble figuring out the reason my JavaScript code isn't functioning properly. Any ideas?

Just starting out with javascript and running into an issue, This snippet of code seems to be working as expected: function test(args){ return "12345 - "+args; } console.log(test("678910")); However, this other piece of code is ...

Sending the Request Body from Angular to a RESTful API

My RESTful controller is not receiving the Request Body from an Angular POST, and I'm struggling to figure out why. Take a look at the code snippet from my controller: adminController.controller('ModalCtrl', ['$scope', '$mod ...

Using React Bootstrap: Passing an array to options in Form.Control

I'm currently utilizing Form.Control to generate a dropdown list and I want the list to be dynamic. Here is my code snippet: render() { return ( <Form.Control as="select" value={this.state.inputval} onChange={this.updateinputval}> ...

Assistance with organizing date schedules using Javascript

I'm currently assisting a friend with his small project, and we've run into an interesting situation. Imagine a scenario where a doctor informs their patient that starting today, they have X number of consultations scheduled for every Wednesday a ...

Error Message: Error Code 2. I am encountering an issue with the bot expecting either undefined or null and receiving a string primitive instead. Any

As I delved into creating a music bot with support for slash commands, everything seemed to be going smoothly when embedding a URL to a single song. However, the trouble began when attempting to include a link to a playlist, resulting in two perplexing err ...

How can I install fs and what exactly does it do in JavaScript?

As a beginner in the world of JavaScript, I am struggling with what seems like a basic issue. In my journey to develop some JavaScript code and utilize sql.js, I keep encountering an error at this line: var fs = require('fs'); This error is due ...

Looking for assistance with transferring API information to components

I am currently working on a basic Movie finder application that will display a list of movies containing the name entered by the user. My focus at this stage is to just show the information on the screen. As I'm using React for this project, I have t ...

The angular filter I implemented is running thrice before yielding no result

I have been facing an issue with my filter where it runs three times in total. The first execution returns the desired results, but the subsequent two executions return nothing. I am puzzled as to why the filter is being called two more times than expected ...

Using $index in ng-class to dynamically apply form validation styles

Looking to validate an angular form input and add a class if it's not $valid. The catch is, it's nested inside an ng-repeat looping through an array of integers, with the input name based on the $index: <li ng-repeat="item in selectedItem.dat ...

Retrieving the output from a function in Angular

Below is the scope function present in my controller: $scope.getStaff = function (request, response) { var a = []; if ($scope.staff !== null) { // All terms must be contained a = $scope.staff; var terms = request.term.toLo ...

Encountering an error with my JSONP call

Similar Question: json with google geocoding api json Uncaught SyntaxError: Unexpected token : $.getJSON('http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true&callback=?', function(data) { ...

The function called Nuxt: n2 is not defined

When using Nuxt 3, I encountered a TypeError that looks like the following: Uncaught TypeError: n2 is not a function My issue revolves around a button that triggers the function toggleSelectRow with a @click.prevent directive. The function in question is ...

How exactly does this JavaScript code determine the index of the maximum value within an array?

Examining the specific line of code: let largest = arr.reduce((a,v,i) => v > a[1] ? [i,v] : a, [-1,0]); I find this part a, [-1,0] particularly perplexing, as I am unsure of its syntax. How does a function before the comma? ...

Combining Mongoose query results in a for loop: A step-by-step guide

i am trying to combine the results of a mongoose query into a single JSON object. however, i am encountering an issue where i am passing an array to mongoose. specifically, the array looks like this: Modem Serial: [11111111111,nodata,3333333333333333] wh ...

Tasks should be defined prior to being referenced in order to avoid any issues

Utilizing multiple files with gulp@4, the main gulpfile.js includes all other files within the ./tasks/ directory. We have implemented the npm gulp-hub package to incorporate multiple gulpfiles within the ./tasks/ directory. However, upon calling the tasks ...

Bootstrap - Input fields not following grid constraints

I have scoured the internet for answers to my question and haven't found anything useful, not even in previous posts on this forum. Currently, I am working on a website for internal company use and tinkering with it at home. However, I seem to be fac ...

Is it necessary to generate a file for each API in Next.js?

When working with Next.js, it is common practice to create a separate file for each new API endpoint. For example, for the /user endpoint, there would be a user.js file with its own handler, and another one for /user/goldmember. Some may argue that this ...

Looking to transform a string into JSON format using LogStash

Currently, I am facing an issue with how Logstash is handling a specific field in JSON format. The problem arises from Logstash treating this field as a string due to the presence of quotes around the value. My goal is to have Logstash interpret the conten ...

Dart and external CSS and JS libraries and tools

As I prepare to dive into developing my very first web application, one technology that has caught my eye is Google Dart. The idea of using a new, innovative approach to web development excites me, and I am seriously considering utilizing it for my project ...