JSON 如何获取 Key 值:全面指南与实用代码示例
在处理 JSON 数据时,获取其中的键(Key)值是一项基础且重要的操作,无论是前端开发中的数据解析,还是后端服务的数据处理,如何高效获取 JSON 的 Key 都是必备技能,本文将详细介绍在不同编程语言中获取 JSON Key 值的方法,并提供实用的代码示例。
JSON 基础回顾
让我们简单回顾一下 JSON 的结构,JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,采用键值对(Key-Value)的方式来组织数据,一个典型的 JSON 对象如下:
{
"name": "张三",
"age": 30,
"isStudent": false,
"courses": ["数学", "英语"],
"address": {
"city": "北京",
"district": "朝阳区"
}
}
在这个例子中,"name"、"age"、"isStudent" 等都是 Key,而它们对应的值(如 "张三"、30、false)则是 Value。
在 JavaScript 中获取 JSON Key 值
JavaScript 是处理 JSON 的原生语言,提供了多种获取 Key 的方法。
使用 Object.keys() 方法
Object.keys() 方法返回一个包含对象所有可枚举属性(Key)的数组。
const jsonData = {
"name": "张三",
"age": 30,
"isStudent": false
};
const keys = Object.keys(jsonData);
console.log(keys); // 输出: ["name", "age", "isStudent"]
使用 for...in 循环
for...in 循环可以遍历对象的可枚举属性(包括原型链上的属性)。
const jsonData = {
"name": "张三",
"age": 30,
"isStudent": false
};
for (let key in jsonData) {
console.log(key); // 依次输出: "name", "age", "isStudent"
}
使用 Object.getOwnPropertyNames() 方法
Object.getOwnPropertyNames() 方法返回一个包含对象自身所有属性(包括不可枚举属性)的数组。
const jsonData = {
"name": "张三",
"age": 30,
"isStudent": false
};
const keys = Object.getOwnPropertyNames(jsonData);
console.log(keys); // 输出: ["name", "age", "isStudent"]
获取嵌套 JSON 的 Key
对于嵌套的 JSON 对象,可以使用递归的方式获取所有 Key:
function getAllKeys(obj, parentKey = '') {
let keys = [];
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
const fullKey = parentKey ? `${parentKey}.${key}` : key;
keys.push(fullKey);
if (typeof obj[key] === 'object' && obj[key] !== null) {
keys = keys.concat(getAllKeys(obj[key], fullKey));
}
}
}
return keys;
}
const nestedJson = {
"name": "张三",
"address": {
"city": "北京",
"district": "朝阳区"
}
};
console.log(getAllKeys(nestedJson));
// 输出: ["name", "address", "address.city", "address.district"]
在 Python 中获取 JSON Key 值
Python 的 json 模块提供了处理 JSON 数据的功能。
解析 JSON 并获取 Key
首先使用 json.loads() 将 JSON 字符串解析为 Python 字典,然后使用 keys() 方法获取所有 Key。
import json
json_str = '{"name": "张三", "age": 30, "isStudent": false}'
json_data = json.loads(json_str)
keys = json_data.keys()
print(list(keys)) # 输出: ['name', 'age', 'isStudent']
使用 for 循环遍历 Key
import json
json_str = '{"name": "张三", "age": 30, "isStudent": false}'
json_data = json.loads(json_str)
for key in json_data:
print(key) # 依次输出: "name", "age", "isStudent"
获取嵌套 JSON 的 Key
可以使用递归函数获取嵌套 JSON 的所有 Key:
import json
def get_all_keys(obj, parent_key=''):
keys = []
for key in obj:
full_key = f"{parent_key}.{key}" if parent_key else key
keys.append(full_key)
if isinstance(obj[key], dict):
keys.extend(get_all_keys(obj[key], full_key))
return keys
json_str = '''{
"name": "张三",
"address": {
"city": "北京",
"district": "朝阳区"
}
}'''
json_data = json.loads(json_str)
print(get_all_keys(json_data))
# 输出: ['name', 'address', 'address.city', 'address.district']
在 Java 中获取 JSON Key 值
Java 中处理 JSON 常用的库有 org.json、Gson 和 Jackson,这里以 org.json 为例。
使用 org.json 库
首先添加依赖(Maven):
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>
然后获取 Key:
import org.json.JSONObject;
public class JsonKeyExample {
public static void main(String[] args) {
String jsonStr = "{\"name\": \"张三\", \"age\": 30, \"isStudent\": false}";
JSONObject jsonObject = new JSONObject(jsonStr);
// 获取所有 Key
for (String key : jsonObject.keySet()) {
System.out.println(key);
}
}
}
// 输出: "name", "age", "isStudent"
获取嵌套 JSON 的 Key
import org.json.JSONObject;
public class NestedJsonKeyExample {
public static void main(String[] args) {
String jsonStr = "{"
+ "\"name\": \"张三\","
+ "\"address\": {"
+ " \"city\": \"北京\","
+ " \"district\": \"朝阳区\""
+ "}"
+ "}";
JSONObject jsonObject = new JSONObject(jsonStr);
getAllKeys(jsonObject, "");
}
public static void getAllKeys(JSONObject obj, String parentKey) {
for (String key : obj.keySet()) {
String fullKey = parentKey.isEmpty() ? key : parentKey + "." + key;
System.out.println(fullKey);
if (obj.get(key) instanceof JSONObject) {
getAllKeys(obj.getJSONObject(key), fullKey);
}
}
}
}
// 输出: "name", "address", "address.city", "address.district"
在 PHP 中获取 JSON Key 值
PHP 提供了 json_decode() 函数来解析 JSON 字符串。
解析 JSON 并获取 Key
<?php
$jsonStr = '{"name": "张三", "age": 30, "isStudent": false}';
$jsonData = json_decode($jsonStr, true); // 第二个参数 true 返回数组
foreach ($jsonData as $key => $value) {
echo $key . "\n";
}
// 输出: "name", "age", "isStudent"
?>
获取嵌套 JSON 的 Key
<?php
function getAllKeys($obj, $parentKey = '') {
$keys = [];
foreach ($obj as $key => $value) {
$fullKey = $parentKey ? $parentKey . '.' . $key : $key;
$keys[] = $fullKey;
if (is_array($value)) {
$keys = array_merge($keys, getAllKeys($value, $fullKey));
}
}
return $keys;
}
$jsonStr = '{
"name": "张三",
"address": {
"city": "北京",
"district": "朝阳区"
}
}';
$jsonData = json_decode($jsonStr, true);
print_r(getAllKeys($jsonData));
// 输出: Array ( [0] => name [1] => address [2] => address.city [3] => address.district )
?>
获取 JSON 的 Key 值是处理 JSON 数据的基础操作,不同编程语言提供了各自的方法来实现这一功能:
- JavaScript:
Object.keys()、for...in循环 - Python:
json.loads()+keys()或直接遍历字典 - Java:
org.json库的keySet()方法 - PHP:
json_decode()+ 遍历数组
对于嵌套的 JSON 结构,通常需要使用递归方法来获取所有层级的 Key,这些方法将帮助你在各种开发场景中



还没有评论,来说两句吧...