C# 遍历JSON

  1.             string test_json = "{\"name\":\"tom\",\"nickname\":\"tony\",\"sex\":\"male\",\"age\":20,\"email\":\"123@123.com\"}";  
  2. var o = JObject.Parse(yourJsonString);  
  3.   
  4.             foreach (JToken child in o.Children())  
  5.             {  
  6.                 var property1 = child as JProperty;  
  7.                 MessageBox.Show(property1.Name + ":" + property1.Value);  
  8. }  

多层Json

[csharp]  view plain  copy
  1. var o = JObject.Parse(yourJsonString);  
  2.   
  3. foreach (JToken child in o.Children())  
  4. {  
  5.     //var property1 = child as JProperty;  
  6.     //MessageBox.Show(property1.Name + ":" + property1.Value);  
  7.     foreach (JToken grandChild in child)  
  8.     {  
  9.         foreach (JToken grandGrandChild in grandChild)  
  10.         {  
  11.             var property = grandGrandChild as JProperty;  
  12.             if (property != null)  
  13.             {  
  14.                 MessageBox.Show(property.Name + ":" + property.Value);  
  15.             }  
  16.         }  
  17.     }  
  18. }  
遍历 JSON 数据结构是处理数据交换和解析时的常见需求。JSON 本质上是一种嵌套的数据格式,通常以键值对(对象)或数组形式表示。不同编程语言提供了不同的方法来实现 JSON 数据的遍历。 ### 使用 Python 遍历 JSON 数据 Python 提供了内置的 `json` 模块用于解析和处理 JSON 数据[^3]。在解析之后,可以使用递归函数遍历 JSON 结构中的所有元素。 #### 示例:将 JSON 字符串转换为 Python 对象并遍历 ```python import json # JSON 字符串 json_str = ''' { "name": "Alice", "age": 25, "skills": ["Python", "JavaScript"], "address": { "city": "New York", "zip": "10001" } } ''' # 解析 JSON 字符串 data = json.loads(json_str) # 定义递归函数遍历 JSON 数据 def traverse_json(obj, indent=0): if isinstance(obj, dict): for key, value in obj.items(): print(' ' * indent + f"Key: {key}") traverse_json(value, indent + 4) elif isinstance(obj, list): for index, item in enumerate(obj): print(' ' * indent + f"Index: {index}") traverse_json(item, indent + 4) else: print(' ' * indent + f"Value: {obj}") # 调用函数 traverse_json(data) ``` 输出结果: ``` Key: name Value: Alice Key: age Value: 25 Key: skills Index: 0 Value: Python Index: 1 Value: JavaScript Key: address Key: city Value: New York Key: zip Value: 10001 ``` ### 使用 JavaScript 遍历 JSON 数据 JavaScript 是 JSON 的起源语言,因此原生支持 JSON 数据的解析与遍历。可以通过递归函数轻松实现 JSON 的深度遍历。 #### 示例:遍历 JSON 对象 ```javascript // JSON 数据 const jsonData = { name: "Bob", age: 30, hobbies: ["reading", "coding"], contact: { email: "bob@example.com", phone: "123-456-7890" } }; // 递归遍历函数 function traverseJson(obj, indent = 0) { if (Array.isArray(obj)) { obj.forEach((item, index) => { console.log(' '.repeat(indent) + `Index: ${index}`); traverseJson(item, indent + 4); }); } else if (typeof obj === 'object' && obj !== null) { for (const key in obj) { console.log(' '.repeat(indent) + `Key: ${key}`); traverseJson(obj[key], indent + 4); } } else { console.log(' '.repeat(indent) + `Value: ${obj}`); } } // 调用函数 traverseJson(jsonData); ``` 输出结果: ``` Key: name Value: Bob Key: age Value: 30 Key: hobbies Index: 0 Value: reading Index: 1 Value: coding Key: contact Key: email Value: bob@example.com Key: phone Value: 123-456-7890 ``` ### 其他语言遍历 JSON 的简要说明 - **Java**:可以使用 `org.json` 或 `Gson` 等库进行 JSON 解析,并通过递归方法遍历对象。 - **C#**:使用 `Newtonsoft.Json`(也称为 Json.NET)库,支持 LINQ 查询和深度遍历。 - **PHP**:使用 `json_decode()` 函数将 JSON 数据转换为 PHP 数组,然后使用 `foreach` 进行遍历。 ### 总结 无论使用哪种编程语言,遍历 JSON 数据的核心在于理解其嵌套结构,并使用递归函数来访问每一层的数据节点。Python 和 JavaScript 提供了简洁的方法来实现这一目标,同时保持代码的可读性和可维护性。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值