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

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.

主站蜘蛛池模板: 深州市| 巴楚县| 维西| 安庆市| 固原市| 正蓝旗| 资兴市| 平安县| 昌都县| 河津市| 汝阳县| 安宁市| 临夏县| 新乐市| 赞皇县| 高雄县| 金塔县| 德阳市| 安龙县| 淅川县| 牡丹江市| 开封县| 沭阳县| 荆州市| 双桥区| 会同县| 崇义县| 周宁县| 威宁| 资兴市| 庄河市| 昂仁县| 响水县| 娄烦县| 阳山县| 长子县| 华坪县| 清流县| 五常市| 乡城县| 嫩江县|