JSFiddle - React, Tailwind, and code Playground
by ryanwheale
HTML
<p>The difference between <code>obj</code> and <code>jsonStr</code> is that <code>obj</code> is a real JavaScript object with real properties (fields) which can be accessed like <code>obj.firstName</code> or modified like <code>obj.firstName = "Dave";</code>. On the other hand <code>jsonStr</code> is simply a string... which is an arbirary series of characters (letters, numbers, symbols).</p>
<p>Technically speaking, there is no difference between <code>str</code> and <code>jsonStr</code> - they are both an arbitrary sequence of characters. However, we can clearly see that <code>jsonStr</code> looks a lot like <code>obj</code>. In such cases, we can parse <code>jsonStr</code> and turn it into a real JavaScript object.</p>
<pre id="logger"></pre>
CSS
code {
padding: 0 .3em;
background-color: #eee;
}
JavaScript
jQuery(function($) {
var obj = {firstName: 'Joe', lastName: 'Schmoe'};
var str = 'Some string';
var jsonStr = '{"firstName": "Susan", "lastName": "Smith"}';
print('// Let\'s define some variables (take note of the quotes):');
print('var obj == {firstName: \'Joe\', lastName: \'Schmoe\'};');
print('var str == \'Some string\';');
print('var jsonStr == \'{"firstName": "Susan", "lastName": "Smith"}\';');
print('\n// Different variables have different types:');
print('typeof obj == ' + typeof obj + ';');
print('typeof str == ' + typeof str + ';');
print('typeof jsonStr == ' + typeof jsonStr + ';');
print('\n// Objects have properties (fields). Strings do not:');
print('obj.firstName == ' + obj.firstName + ';');
print('jsonStr.firstName == ' + jsonStr.firstName + ';');
var newObj = JSON.parse(jsonStr);
print('\n// You can convert properly formatted strings to objects.\n// NOTE: The string must be in proper JSON format:');
print('var newObj = JSON.parse( jsonStr );');
newObj.firstName = "Susie";
print('\n// Turns out Susan likes to go by Susie!');
print('newObj.firstName = "' + newObj.firstName + '";');
jsonStr = JSON.stringify(newObj);
print('\n// Now that we have updated the object, lets turn it back into a string:');
print('jsonStr = JSON.stringify(newObj);');
print('\n// Here is the value of jsonStr:');
print(jsonStr);
function print( msg ) {
$('#logger').html( $('#logger').html() + '\n' + msg );
}
});