如何读取非自定义JSON格式文件中的字符串数组数据
提取嵌套JSON数组中的所有字符串值
嘿,我来帮你搞定这个问题!你的example.json是一个嵌套的二维数组,目标是把里面所有的字符串提取出来存成一个扁平的列表/数组对吧?下面给你几种常用编程语言的实现方案,按需选择就行:
Python 实现
如果用Python处理,有两种常见方式:一种是针对已知二维结构的快速写法,另一种是支持任意嵌套深度的通用递归方法。
import json # 第一步:读取JSON文件内容 with open('example.json', 'r') as file: nested_data = json.load(file) # 方法1:列表推导式(适合确定是二维数组的场景) flat_list = [item for sublist in nested_data for item in sublist] # 方法2:递归函数(支持任意层级的嵌套数组,更通用) def flatten_nested(nested): result = [] for element in nested: if isinstance(element, list): result.extend(flatten_nested(element)) else: # 如果你只想提取字符串,可以加个类型判断:if isinstance(element, str) result.append(element) return result flat_list_recursive = flatten_nested(nested_data) # 两种方法的输出都是:['fight', 'gunshot', 'fleeing', 'gunshot', 'falling', 'fleeing'] print(flat_list)
JavaScript (Node.js) 实现
如果在Node.js环境下处理,同样有简洁的内置方法和通用的递归方案:
const fs = require('fs'); // 读取并解析JSON文件 const nestedData = JSON.parse(fs.readFileSync('example.json', 'utf8')); // 方法1:使用Array.flat()(ES2019及以上版本支持,一键扁平化) const flatArray = nestedData.flat(Infinity); // 方法2:递归函数(兼容性更好,适合旧版Node.js环境) function flattenNested(arr) { let result = []; arr.forEach(element => { if (Array.isArray(element)) { result = result.concat(flattenNested(element)); } else { // 如需仅提取字符串,可添加判断:if (typeof element === 'string') result.push(element); } }); return result; } const flatArrayRecursive = flattenNested(nestedData); // 输出结果一致:['fight', 'gunshot', 'fleeing', 'gunshot', 'falling', 'fleeing'] console.log(flatArray);
小提示
如果你的JSON数据里除了字符串还有其他类型(比如数字、布尔值),可以在代码里加上类型判断,确保只提取字符串值——上面的代码注释里已经标出来了,按需启用就行。
内容的提问来源于stack exchange,提问作者Hasan Kaan TURAN
相关产品推荐
相关产品推荐

