JavaScript programmers love JSON because it is “baked-in” to the JavaSCript programmnig language.
For those of using C#, Python, or Java, we have to use class libraries to assist us with the normal functions that are super-easy in JavaScript.
This blog shows you most of you what you need to know about JSON in one sample program. Ok, granted, I don’t show you how to do a request/response to a REST web service, but that’s only way one JSON is used.
<pre>
console.log("-------------------- Start JSON Demo:" + (new Date()).toLocaleString());
// Show how it easy it is to create a real object in
// Javascript on the fly, with values, in one line of code!
var flightObject = { flightNumber: "2501", passenger: "Neal Walters", DepartureAirport: "DFW", ArrivalAirport: "LAX"};
// Immediately you are able to access the properties
// of that object.
console.log("FlightNumber=" + flightObject.flightNumber);
console.log("Passenger=" + flightObject.passenger);
// Dynamically add a new properties to the object
flightObject.Airline = "Southwest Airlines";
flightObject.AirlineCode = "WN";
// Now deserialize the object to a JSON string
// (couldn't they have called the method JSON.deserialize?)
var flightJSONString = JSON.stringify(flightObject);
console.log("flightJSONString=" + flightJSONString);
// Now create a new object from a JSON string
// (couldn't they have called the method JSON.serialize?)
var flightObj2 = JSON.parse(flightJSONString)
console.log("flightObj2.AirlineName=" + flightObj2.Airline);
console.log("-------------------- End JSON Demo:" + (new Date()).toLocaleString());
</pre></con>
<h4>Sample output</h4>
<code><pre>
-------------------- Start JSON Demo:6/12/2020, 10:22:11 AM
flightObject=[object Object]
FlightNumber=2501
Passenger=Neal Walters
flightJSONString={"flightNumber":"2501","passenger":"Neal Walters","DepartureAirport":"DFW","ArrivalAirport":"LAX","Airline":"Southwest Airlines","AirlineCode":"WN"}
flightObj2.AirlineName=Southwest Airlines
-------------------- End JSON Demo:6/12/2020, 10:22:11 AM
</pre>
By the way, you can run the code above in VSCode. Just install “Code Runner”. Save your file, and use CNTL-ALT-N to run it.
In the extension manager, you can choose options to auto-save the file before running it (otherwise it runs what is on disk, and not what is in memory). There is also an option to clear the output windows on each run.
Another trick of “Code Runner” is that you can highlight the lines of code you want to run, then press the CNTL-ALT-N hot key, and it just runs those lines of code.
The official way in VSCode to run an extension is to press F1, search for the extension. In this case, like for “run code” (not “code Runner”), and select it. But after a while, I’m sure you will start using the short-cut key.