While reading from a JSON is done to bind the value to User Interface, writing is done prepare a data object that can be to an API.
Here, again we’re going to write to a JSON via JavaScript, to not rely on any external dependency for now.
stringify()
is an in-built method in JavaScript, that lets you write a JSON Array or an Object. Here is an example of writing a JSON Object:
console.log(JSON.stringify({ trainNumber: 12055, trainName: "DDN JAN-SHATABDI"}));
Output:
{
"trainNumber": 12055,
"trainName": "DDN JAN-SHATABDI"
}
Writing a JSON Array:
console.log(
JSON.stringify(
{ trains:
[
{ trainNumber: 12055, trainName: 'DDN JAN-SHATABDI'},
{ trainNumber: 12013, trainName: 'ASR SHATABDI'},
{ trainNumber: 12005, trainName: 'KALKA SHATABDI'}
]
}
));
Output:
"trains":[
{"trainNumber":12055, "trainName":"DEHRADUN JAN-SHATABDI"},{"trainNumber":12013, "trainName":"ASR SHATABDI"},
{"trainNumber":12005, "trainName":"KALKA SHATABDI"}
]
In next parts, we’ll learn how to write JSON in other languages.
Leave a Reply