JSON Parent to have total amount of child field

I am mocking out a JSON object where I want the sum of all child service lines to be added and be on the invoice level.

invoice.Amount = sum(invoice.serviceLine.amount)

My apologies if I missed seeing this in another post.

Something like this? http://mockaroo.com/943cff30

Here I use a formula to sum the amount values:

serviceLine.map {|l| l['amount']}.sum

Yes, that’s what I’d like to do, but the nature of the document has the invoice sum at the top of the document not the bottom. When I move the sum to be at the top, it can’t find the amount field, I think I saw elsewhere that the formula has to appear after the field it’s referencing. Per the standard of the document, I need it at the top. Is there anyway around that?

My only other thoughts, were to write something that read through the JSON object and put the summations in where I needed them.

Thank you for the very quick reply!

That is correct, formulas must always appear after the fields they depend on as the fields are generated in the order in which they appear in the schema. You’d either need to postprocess the data or make the argument that field order in json shouldn’t matter :slight_smile:

You’re right. It doesn’t matter. I’m trying to mock a JSON version of an x12 EDI document. The x12 cares, but the JSON doesn’t since I wouldn’t be parsing it with the x12 standard anyway… Thanks!

How do we modify the formula if we have to sum up the values at 3 levels. Tried something like

serviceline.productgroup.map {|l| l[‘amount’]}.sum and

serviceline.productgroup.map {|l||l| l[‘amount’]}.sum

Both these did not work. If the syntax could be explained that would be helpfull.