在 JavaScript 中解析 JSON 以显示特定的名称/值对?

javascriptweb developmentobject oriented programming更新于 2025/10/30 3:56:17

要解析 JSON,请使用 parseJSON();要显示特定的对,请使用 $.each() 函数。

假设以下是我们的 JSON,解析结果为 −

const APIData =
'[{"Name":"John","Age":21},{"Name":"David","Age":24},{"Name":"Bob","Age" :20}]';
const getObject = jQuery.parseJSON(APIData);

现在,让我们查看完整代码并获取"Name"对 −

示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=
1.0">
<title>Document</title>
</head>
<link rel="stylesheet"
href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<body>
<script>
   const APIData =
   '[{"Name":"John","Age":21},{"Name":"David","Age":24},{"Name":"Bob","Age":20}]';
   const getObject = jQuery.parseJSON(APIData);
   $.each(getObject, function (k,obj) {
      console.log(obj['Name']);
   });
</script>
</body>
</html>

要运行上述程序,请保存文件名"anyName.html(index.html)",然后右键单击该文件。在 VS Code 编辑器中选择选项"使用 Live Server 打开"。

输出

这将产生以下输出。


相关文章


有用资源