# Calculate with grid fields

You can also calculate with grid field values. For example, you can calculate the sum of a row or column in your grid. This of course makes sense if you are using numerical fields, but can sometimes apply to dropdown fields as well.

Grid fields are stored as so-called JSON objects. A JSON object looks like this:

`{"0":{"0":"A","1":"C"},"1":{"0":"B","1":"D"}}`

In this case, the grid field consists of 2 rows, numbered 0 and 1 (outside the inner brackets), and two columns, also numbered 0 and 1 (inside the inner brackets). For the case above, the grid would look like this in Castor: ### Accessing values from the grid field

You will first need to 'parse' the grid field - this will always be your first step and you can use this piece of code for that:

```var obj = JSON.parse('{grid_variable_name}');
```

Afterwards you can do calculations with the individual items.

To get the value entered in the first row and first column, use:

`Object.values(obj);`

To get the value entered in the second row and first column, use:

`Object.values(obj);`

To get the value entered in the second row and second column, use:

`Object.values(obj);`

and so on. You can perform further calculations with these values, depending on what you are trying to achieve.

### Use of numbers in grid fields

Beware that this code above renders the objects in string (plain text). If you want to do mathematical operations with numbers, you will need to convert that text into numbers. For that you would use the parseInt() function. For example, we want to get the sum of the values in the first row of the grid shown below: To get the sum of the first row (in this case it is 16), we would use:

`parseInt(Object.values(obj)) + parseInt(Object.values(obj)); `

You cannot calculate with a (half-)empty grid field - all the cells that are used in the calculation have to be filled in the grid to be able to execute the calculation.

If the numbers contain decimals we will need to use the function parseFloat() instead. For example, we want to get the sum of the values in the first row of the grid shown below: To obtain as result 29.5 we have used this code:

`parseFloat(Object.values(obj)) + parseFloat(Object.values(obj));`

### Validate grid field values

Calculation fields can be used to validate values in the grid field. For example, this template validates the values entered in the first and second columns of the first row.

```var obj = JSON.parse('{grid_variable_name}');

if (Object.values(obj) == 1 && Object.values(obj) == 1) {
'The values are correct!';
} else {
'The values are not correct!';
}```

Use if/else logic to render various data validation messages. Use if/else logic to output a number and add data validation to a calculation to display 'Warning' messages (like the one below) and other types of data validation messages. or drag and drop files