怎么拿到JSON的值:从基础到实践的全面指南
在当今的软件开发中,JSON(JavaScript Object Notation)已成为数据交换的主流格式,无论是调用API接口、解析配置文件,还是处理前后端数据交互,“怎么拿到JSON的值”都是开发者必须的核心技能,本文将从JSON的基础结构讲起,结合不同编程语言的实践方法,带你系统获取JSON值的技巧。
先搞懂:JSON到底是什么?
JSON是一种轻量级的数据交换格式,以键值对(Key-Value Pair)为核心结构,易于人阅读和编写,也易于机器解析和生成,它的基本结构包括两种类型:
对象(Object):用 表示
- 类似于编程语言中的字典、哈希表或对象,由多个键值对组成。
- 键(Key)必须是字符串,值(Value)可以是任意类型(字符串、数字、布尔值、数组、对象甚至null)。
- 键值对之间用逗号 分隔,键和值用冒号 连接。
示例:
{
"name": "张三",
"age": 25,
"isStudent": false,
"courses": ["数学", "英语"],
"address": {
"city": "北京",
"district": "海淀区"
}
}
数组(Array):用 [] 表示
- 类似于编程语言中的列表或数组,按顺序排列多个值。
- 数组中的值(元素)可以是任意类型(包括对象、数组等)。
示例:
[
{"name": "李四", "age": 30},
{"name": "王五", "age": 28}
]
核心场景:如何拿到JSON的值?
获取JSON的值,本质是通过键(Key)或索引(Index)定位目标数据,根据JSON结构(对象、数组、嵌套结构),方法略有不同,以下以常见编程语言为例,结合具体场景讲解。
场景1:解析简单的JSON对象(无嵌套)
假设有以下JSON对象(字符串形式):
const jsonStr = '{"name": "张三", "age": 25, "isStudent": false}';
目标:获取 name 和 age 的值。
JavaScript(前端/Node.js)
JavaScript原生支持JSON,通过 JSON.parse() 将字符串转为对象,再通过键访问:
const jsonObj = JSON.parse(jsonStr); // 解析为对象 const name = jsonObj.name; // 或 jsonObj["name"] const age = jsonObj.age; console.log(name, age); // 输出:张三 25
Python
Python使用 json 模块解析字符串,转为字典后通过键访问:
import json
json_str = '{"name": "张三", "age": 25, "isStudent": false}'
json_obj = json.loads(json_str) # 解析为字典
name = json_obj["name"]
age = json_obj["age"]
print(name, age) # 输出:张三 25
Java
Java可以使用 org.json 库(如 JSONObject)或Jackson/Gson等第三方库:
import org.json.JSONObject;
public class JsonExample {
public static void main(String[] args) {
String jsonStr = "{\"name\": \"张三\", \"age\": 25}";
JSONObject jsonObj = new JSONObject(jsonStr);
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
System.out.println(name + " " + age); // 输出:张三 25
}
}
场景2:解析JSON数组(含多个对象)
假设有以下JSON数组:
const jsonArrayStr = '[{"name": "李四", "age": 30}, {"name": "王五", "age": 28}]';
目标:获取第一个人的 name 和所有人的 age。
JavaScript
数组通过索引访问,结合对象键获取值:
const arr = JSON.parse(jsonArrayStr); const firstPersonName = arr[0].name; // 索引0取第一个对象,再取name const allAges = arr.map(person => person.age); // 遍历数组,提取所有age console.log(firstPersonName, allAges); // 输出:李四 [30, 28]
Python
列表通过索引访问,字典通过键访问:
import json
json_array_str = '[{"name": "李四", "age": 30}, {"name": "王五", "age": 28}]'
arr = json.loads(json_array_str)
first_person_name = arr[0]["name"]
all_ages = [person["age"] for person in arr]
print(first_person_name, all_ages) # 输出:李四 [30, 28]
Java
使用 JSONArray 解析数组,遍历取值:
import org.json.JSONArray;
import org.json.JSONObject;
public class JsonArrayExample {
public static void main(String[] args) {
String jsonArrayStr = "[{\"name\": \"李四\", \"age\": 30}, {\"name\": \"王五\", \"age\": 28}]";
JSONArray arr = new JSONArray(jsonArrayStr);
JSONObject firstPerson = arr.getJSONObject(0);
String firstPersonName = firstPerson.getString("name");
for (int i = 0; i < arr.length(); i++) {
JSONObject person = arr.getJSONObject(i);
System.out.println(person.getString("name") + ": " + person.getInt("age"));
}
}
}
场景3:解析嵌套JSON(对象套对象/数组)
假设有以下复杂JSON:
const nestedJsonStr = '{
"name": "张三",
"address": {
"city": "北京",
"district": "海淀区"
},
"courses": [
{"name": "数学", "score": 90},
{"name": "英语", "score": 85}
]
}';
目标:获取 city、数学 的分数、courses 数组的长度。
JavaScript
通过“链式访问”逐层定位:
const obj = JSON.parse(nestedJsonStr); const city = obj.address.city; // 对象嵌套:address.city const mathScore = obj.courses[0].score; // 数组+对象嵌套:courses[0].score const coursesLength = obj.courses.length; // 数组长度 console.log(city, mathScore, coursesLength); // 输出:北京 90 2
Python
类似JavaScript,通过多层键/索引访问:
import json
nested_json_str = '''{
"name": "张三",
"address": {
"city": "北京",
"district": "海淀区"
},
"courses": [
{"name": "数学", "score": 90},
{"name": "英语", "score": 85}
]
}'''
obj = json.loads(nested_json_str)
city = obj["address"]["city"]
math_score = obj["courses"][0]["score"]
courses_length = len(obj["courses"])
print(city, math_score, courses_length) # 输出:北京 90 2
Java
嵌套结构需逐层解析对象和数组:
import org.json.JSONObject;
import org.json.JSONArray;
public class NestedJsonExample {
public static void main(String[] args) {
String nestedJsonStr = "{...}"; // 同上JSON字符串
JSONObject obj = new JSONObject(nestedJsonStr);
// 获取city
JSONObject address = obj.getJSONObject("address");
String city = address.getString("city");
// 获取数学分数
JSONArray courses = obj.getJSONArray("courses");
JSONObject mathCourse = courses.getJSONObject(0);
int mathScore = mathCourse.getInt("score");
// 获取courses长度
int coursesLength = courses.length();
System.out.println(city + " " + mathScore + " " + coursesLength);
}
}
场景4:处理动态JSON(键名不确定或结构变化)
实际开发中,JSON的键名可能动态变化(如API返回的字段随请求参数变化),此时需动态获取键。
JavaScript
使用 Object.keys() 获取所有键,或 for...in 遍历键:
const dynamicJson = '{"status": "success", "data": {"userId": 123, "token": "abc123"}}';
const obj = JSON.parse(dynamicJson);
// 动态获取键
const keys = Object.keys(obj.data); // ["userId", "token"]
for (const key in obj.data) {
console.log(key + ": " + obj.data[key]);
}
Python
使用 dict.keys() 或 dict.items() 遍历字典:
import json dynamic



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