參考鏈接:
1、https://www.w3cschool.cn/json/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test JSON</title>
<script>
document.write("Hello JSON!");
var txt = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';
var txtJsonObj = eval("(" + txt + ")");
var jsonParse = JSON.parse(txt);
document.write("<br>");
for (mykey in jsonParse)
{
myEmployeesArray = jsonParse[mykey];
for (myArray in myEmployeesArray)
{
document.write(myArray + ": " + myEmployeesArray[myArray].firstName + "<br>");
}
}
var myJsonStr = jsonParse.toString();
document.write("JSON String: " + myJsonStr + "<br>");
var people =
{
"programmers": [
{ "firstName": "Brett", "lastName": "McLaughlin", "email": "[email protected]" },
{ "firstName": "Jason", "lastName": "Hunter", "email": "[email protected]" },
{ "firstName": "Elliotte", "lastName": "Harold", "email": "[email protected]" }
],
"authors": [
{ "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
{ "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
{ "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
],
"musicians": [
{ "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
{ "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
]
};
var peopleStr = JSON.stringify(people);// trasfer obj to String
document.write("people json string: " + peopleStr + "<br>");
function showName() {
document.getElementById("firstName").innerHTML = txtJsonObj.employees[0].firstName;
document.getElementById("lastName").innerHTML = txtJsonObj.employees[0].lastName;
}
</script>
</head>
<body>
fistName:<span id="firstName"></span><br>
lastName:<span id="lastName"></span><br>
<button onclick="showName()">showName</button>
</body>
</html>