- Learning Node.js Development
- Andrew Mead
- 253字
- 2021-06-30 18:56:56
Defining a string and using in app as an object
Let's get started by making a variable called personString, and we'll to set it equal to a string using single quotes since JSON uses double quotes inside of itself, as shown here:
var personString = '';
Then we'll define our JSON in the quotes. We'll start by opening and closing some curly braces. We'll use double quotes to create our first attribute, which we'll call name, and we'll set that attribute equal to Andrew. This means that after the closing quote, we'll add :; then we'll open and close double quotes again and type the value Andrew, as shown here:
var personString = '{"name": "Andrew"}';
Next up, we can add another property. After the value, Andrew, I'll create another property after the comma, called age, which will be set equal to a number. I can use my colon and then define the number without the quotes, in this case, 25:
var personString = '{"name": "Andrew","age": 25}';
You can go ahead and use your name and your age, obviously, but make sure the rest looks identical to what you see here.
Now, let's say we get the earlier-defined JSON from a server or we grab it from a text file. Currently, it's useless; if we want to get the name value, there is no good way to do that because we're using a string, so personString.name doesn't exist. What we need to do is take the string and convert it back into an object.