Html/Javascript widget

Tuesday, 14 June 2022

understanding how JSON handles integers and strings

In JSON, values must be one of the following data types:

  • a string
  • a number
  • an object (JSON object)
  • an array
  • a boolean
  • null

JSON values cannot be one of the following data types:

  • a function
  • a date
  • undefined

 

Strings in JSON must always be in double quotes.
Example
{"name":"John"}


Numbers can be either an integer or a floating point.
Example
{"age":30}


JSON also supports objects, following the JSON syntax:

"obj name": {"field":value}

if value is a string, must be between double quotes.


"obj name": {"field":"string Value"}

 

The following is an example to illustrate both integers and strings

<!DOCTYPE html>
<html>
<body>
<p id="test"> </p>

<script>
var mytxt='{"emp":[' +
'{"name":"paul","surname":"smith","age":25,
"admission":2015},'+
'{"name":"maria","surname":"sheeva","age":20,
"admission":2016},'+
'{"name":"jon","surname":"shiv","age":27,
"admission":2012}]}';

var obj = eval ("(" + mytxt + ")");
document.getElementById("test").innerHTML =
obj.emp[1].name+ " " + obj.emp[1].surname + " " +
obj.emp[1].age + obj.emp[1].admission;
document.getElementById("test").innerHTML =
obj.emp[0].age + obj.emp[1].age + " " +
obj.emp[2].age;
document.getElementById("test").innerHTML =
obj.emp[2].admission + obj.emp[0].admission +
obj.emp[1].admission;


</script>

</body>


</html>


The output of the code above will be 6043, since document.getElementById receives whatever the containers obj.emp[2].admission, obj.emp[0].admission and obj.emp[1].admission hold, adding up the integer values passed in the parameters (2015+2016+2012)



No comments:

Post a Comment