0

How could I itterate through the json and extract the values for each task (i.e. "AMS Upgrade" and "BMS works" are the tasks) from the following json string, I have tried using the code below, but no success.

note that AMS Upgrade and BMS works are variables so the code should not reference them

during each loop, i want to be able to console log the following

1st loop

Task Description: AMS Upgrade

Total: 30667.303111791967

% Complete to end: 1.0

value claimed: 25799.788761888347

2nd loop

Task Description: BMS works

Total: 35722.8761704046

% Complete to end: 0.1

value claimed: 3572.2876170404597

var data = `{"line_items": {"AMS Upgrade": [{"Total": 30667.303111791967}, {"% Complete to end": 1.0}, {"value claimed": 25799.788761888347}], "BMS works": [{"Total": 35722.8761704046}, {"% Complete to end": 0.1}, {"value claimed": 3572.2876170404597}]}}`


    var obj = JSON.parse(data);					
    console.log("processing data...");
    console.log(obj); 
    console.log(obj.line_items[1].Total);

 

4
  • Which total you want there are two ? expected output please ? Feb 12, 2019 at 5:29
  • need to show all of them, noting that AMS Upgrade and BMS works are variables
    – Ossama
    Feb 12, 2019 at 5:31
  • 1
    Is there an option of fixing the JSON format? The data about the line items each being an array of dictionaries does not seem likely to be what was intended. Feb 12, 2019 at 5:35
  • 1
    The JSON format doesn't make a lot of sense. What's the point of having an array with a bunch of single-value objects? Why not just use one object? Feb 12, 2019 at 5:36

9 Answers 9

1

Here is way using for..in.

const data = {"line_items": 
	{"AMS Upgrade": [
		{"Total": 30667.303111791967},
		{"%Complete to end": 1.0},
		{"value claimed": 25799.788761888347}],
	"BMSworks":	[
		{"Total": 35722.8761704046},
		{"%Complete to end": 0.1},
		{"value claimed": 3572.2876170404597}]
	}
}
let totals = [];
for(let key in data.line_items){
	totals.push(data.line_items[key][0].Total);
}
console.log(totals)
//Combining all other like Total
for(let key in data.line_items){
  console.log("Task Description:" + key);
  data.line_items[key].forEach(value => {
    let k = console.log(`${Object.keys(value)}:${Object.values(value)[0]}`)
  }) 
}

5
  • how can i loop through the json and get on each run all thses values together, the name, Total, %_complete_to_end: and value_claimed
    – Ossama
    Feb 12, 2019 at 5:54
  • @Ossama please tell your expected output.
    – Maheer Ali
    Feb 12, 2019 at 5:56
  • getting there, but i do not wish to push the values and then display at the end. i wish to display the row values for AMS and then loop through and then display the the values for BMS,
    – Ossama
    Feb 12, 2019 at 6:13
  • @Ossama please edit the post and show expected output
    – Maheer Ali
    Feb 12, 2019 at 6:24
  • how can console log "AMS Upgrade" please
    – Ossama
    Feb 12, 2019 at 9:46
1

const obj = {
	"line_items": {
		"AMS Upgrade": [{
			"Total": 30667.303111791967
		}, {
			"% Complete to end": 1.0
		}, {
			"value claimed": 25799.788761888347
		}],
		"BMS works": [{
			"Total": 35722.8761704046
		}, {
			"% Complete to end": 0.1
		}, {
			"value claimed": 3572.2876170404597
		}]
	}
};
  
const totals = Object.keys(obj.line_items).map(valInner => obj.line_items[valInner][0].Total);
console.log(totals);
  
/* Updated code for inner values */
Object.keys(obj.line_items).forEach(valInner => {
  obj.line_items[valInner].forEach((val) => {
    for (const i in val) {
    	console.log(`${i} = ${val[i]}`);
    }
  });
});

2
  • how can i loop through the json and get on each run all thses values together, the name, Total, %_complete_to_end: and value_claimed
    – Ossama
    Feb 12, 2019 at 5:53
  • @Ossama loop the inner array too.
    – Shubham
    Feb 12, 2019 at 5:59
0

try it like this

var obj = JSON.parse(data);                 
console.log("processing data...");
console.log(obj); 
console.log(obj.line_items["AMS Upgrade"][0]);

The line_itmes has "AMS Upgrade" filed and then the "AMS Upgrade" has array. So you have to access through array.

0

ES6 Variant: Works no matter at what index your total lies.

// ES6 variant.


const test = {
	"line_items": {
		"AMS Upgrade": [{
			"Total": 30667.303111791967
		}, {
			"% Complete to end": 1.0
		}, {
			"value claimed": 25799.788761888347
		}],
		"BMS works": [{
			"Total": 35722.8761704046
		}, {
			"% Complete to end": 0.1
		}, {
			"value claimed": 3572.2876170404597
		}]
	}
};

console.log(test["line_items"]["AMS Upgrade"].map(key => key['Total']).filter(val => !!val)[0]);
console.log(test["line_items"]["BMS works"].map(key => key['Total']).filter(val => !!val)[0]);

0

As you want the those items as variable. Look for theKeyWeWantToget variable.

    var data = `{"line_items": {"AMS Upgrade": [{"Total": 30667.303111791967}, {"% Complete to end": 1.0}, {"value claimed": 25799.788761888347}], "BMS works": [{"Total": 35722.8761704046}, {"% Complete to end": 0.1}, {"value claimed": 3572.2876170404597}]}}`

    var obj = JSON.parse(data);					
    console.log("processing data...");
    console.log(obj); 
    var theKeyWeWantToget = "AMS Upgrade";
    console.log(obj.line_items[theKeyWeWantToget][0].Total);
    theKeyWeWantToget = "BMS works";
    console.log(obj.line_items[theKeyWeWantToget][0].Total);

0

This is your JSON string/object

{
    "line_items": {
        "AMS Upgrade": [{
            "Total": 30667.303111791967
        }, {
            "% Complete to end": 1.0
        }, {
            "value claimed": 25799.788761888347
        }],
        "BMS works": [{
            "Total": 35722.8761704046
        }, {
            "% Complete to end": 0.1
        }, {
            "value claimed": 3572.2876170404597
        }]
    }
}

Accessing Total should be

var totals=[]; //array to store totals.
for(var key in obj.line_items)
{
   totals.push(obj.line_items[key][0].Total);
}
3
  • i edited my question sorry, note that the "AMS upgrade" and "BMS works" are variables, if you are able to modify so you do not reference them
    – Ossama
    Feb 12, 2019 at 5:34
  • @Ossama this should get you the Total s provided that it remains in the same position in the array.
    – Ugo Okoro
    Feb 12, 2019 at 5:47
  • how can i loop through the json and get on each run all thses values together, the name, Total, %_complete_to_end: and value_claimed
    – Ossama
    Feb 12, 2019 at 5:53
0

With your original structure, the following will work:

Object.keys(obj.line_items).forEach(key => console.log(obj.line_items[key][0].Total))

The structure you have for the JSON could be improved to make working with it easier. I would recommend something more along the lines of the following if you have control over the source data:

const data = { line_items: [
    { 
       name: "AMS Upgrade"
       total: 30667.303111791967,
       %_complete_to_end: 1.0,
       value_claimed: 25799.788761888347
    },
    {
        name: "BMSworks",
        total: 35722.8761704046,
        %_complete_to_end: 0.1,
        value_claimed: 3572.2876170404597
    }
]}
2
  • how can i loop through the json and get on each run all thses values together, the name, Total, %_complete_to_end: and value_claimed
    – Ossama
    Feb 12, 2019 at 5:53
  • kinda want something like this Object.keys(obj.line_items).forEach( key => console.log(obj.line_items[key][0].Total ); key => console.log(obj.line_items[key][0].claimed ); )
    – Ossama
    Feb 12, 2019 at 6:19
0

You can take the values and get the total out of from value. Since in your structure you have total only at 0th index you can directly access 0th index if order is not fixed than you can use find.

let obj = {"line_items": {"AMS Upgrade": [{"Total": 30667.303111791967}, {"% Complete to end": 1.0}, {"value claimed": 25799.788761888347}], "BMS works": [{"Total": 35722.8761704046}, {"% Complete to end": 0.1}, {"value claimed": 3572.2876170404597}]}}
let Total = Object.values(obj.line_items).map(e=>e[0].Total)

console.log(Total)

how can i loop through the json and get on each run all thses values together, the name, Total, %_complete_to_end: and value_claimed

let obj = {"line_items": {"AMS Upgrade": [{"Total": 30667.303111791967}, {"% Complete to end": 1.0}, {"value claimed": 25799.788761888347}], "BMS works": [{"Total": 35722.8761704046}, {"% Complete to end": 0.1}, {"value claimed": 3572.2876170404597}]}}

let Total = Object.values(obj.line_items).map(e=> e.map(el=> Object.values(el)))

console.log(Total)

6
  • how can i loop through the json and get on each run all thses values together, the name, Total, %_complete_to_end: and value_claimed
    – Ossama
    Feb 12, 2019 at 5:54
  • @Ossama check the update. structure can be changed if you want. i am just giving value of each element in array Feb 12, 2019 at 5:57
  • description is missing
    – Ossama
    Feb 12, 2019 at 5:59
  • @Ossama you want key value pair ? Feb 12, 2019 at 6:01
  • i basically want to get all the values from the json, so that i can input them in a table. so we can possibly loop through the json, and on each loop get all following (name, Total, %_complete_to_end: and value_claimed) so then i can insert in a table
    – Ossama
    Feb 12, 2019 at 6:02
0

In the first part I'm just parsing JSON data, after I store each array in a variable (this is not necessary) and in the third part I make a console.log of each element of the array

/**
*Part 1
*/
var data = JSON.parse(`{"line_items": {"AMS Upgrade": [{"Total": 30667.303111791967}, {"% Complete to end": 1.0}, {"value claimed": 25799.788761888347}], "BMS works": [{"Total": 35722.8761704046}, {"% Complete to end": 0.1}, {"value claimed": 3572.2876170404597}]}}`);
/**
*Part 2
*/

var amsUpgrade = data['line_items']['AMS Upgrade'];
console.log('AMS Upgrade : ', amsUpgrade);
/**
*Part 3
*/
console.log('AMS Upgrade Total : ', amsUpgrade[0]['Total']);
console.log('AMS Upgrade % Complete to end : ', amsUpgrade[1]['% Complete to end']);
console.log('AMS Upgrade value claimed', amsUpgrade[2]['value claimed']);

var bmsWorks = data['line_items']['BMS works'];
console.log('BMS works : ', bmsWorks);
console.log('BMS works Total : ', bmsWorks[0]['Total']);
console.log('BMS works % Complete to end : ', bmsWorks[1]['% Complete to end']);
console.log('BMS works value claimed', bmsWorks[2]['value claimed']);

3
  • Thanks Mate, my json string does not always have the values AMS Upgrade or BMS works, thses are variables, but the format is the same, your answer seems the best if you can try to remove reference to this
    – Ossama
    Feb 12, 2019 at 6:11
  • I forgot that amsUpgrade.map( amsUpgradeTotal => { if( amsUpgradeTotal.Total != undefined){ console.log("AMS Upgrade Total", amsUpgradeTotal.Total) } }) bmsWorks.map( bmsWorksTotal => { if( bmsWorksTotal.Total != undefined){ console.log("BMS works Total", bmsWorksTotal.Total) } })
    – Madi Naf
    Feb 12, 2019 at 6:24
  • you are directly referring to ['AMS Upgrade'], this is a variable and will change next time i request the json. can you refine without reference to the specific text
    – Ossama
    Feb 12, 2019 at 9:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.