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

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.

主站蜘蛛池模板: 文安县| 高青县| 桐城市| 益阳市| 定襄县| 肇州县| 堆龙德庆县| 高雄市| 通许县| 普定县| 子长县| 桦甸市| 利川市| 美姑县| 西城区| 闵行区| 蓝山县| 观塘区| 山东| 固镇县| 咸宁市| 永川市| 墨竹工卡县| 德钦县| 腾冲县| 信丰县| 烟台市| 徐汇区| 馆陶县| 宝兴县| 巴东县| 库伦旗| 巩留县| 九寨沟县| 武城县| 南通市| 称多县| 辉县市| 扎鲁特旗| 合作市| 平和县|