官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 永寿县| 万年县| 左云县| 鸡泽县| 章丘市| 乐业县| 咸阳市| 寻甸| 聊城市| 新安县| 新乡县| 济阳县| 和静县| 平塘县| 旺苍县| 如东县| 视频| 沙河市| 通化市| 白玉县| 明光市| 若羌县| 南丰县| 武川县| 祁东县| 科尔| 荔波县| 望奎县| 康定县| 静安区| 屯昌县| 分宜县| 西吉县| 杂多县| 遂昌县| 韶关市| 油尖旺区| 刚察县| 广宗县| 杭锦旗| 武平县|