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

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.

主站蜘蛛池模板: 濉溪县| 陇川县| 洮南市| 厦门市| 侯马市| 自贡市| 新乡市| 绥滨县| 乐山市| 湘乡市| 青冈县| 镇远县| 武川县| 贵南县| 来安县| 融水| 常熟市| 永胜县| 东辽县| 三原县| 乌拉特前旗| 榆林市| 伊宁县| 涞源县| 莱阳市| 扶沟县| 茂名市| 云安县| 漳州市| 万载县| 黄石市| 东乡县| 神池县| 辉南县| 关岭| 通海县| 周宁县| 三河市| 嘉义县| 吴堡县| 新昌县|