JavaScript中如何访问无效JSON格式output变量中的response参数
拼接JSON字符串的response参数访问方案
现有问题中的output变量由两个独立JSON对象直接拼接而成,没有合法JSON的分隔符或外层结构,可通过以下两种常用方案处理后访问response参数:
方案1:补全为合法JSON数组(最简便,适合无特殊字符的场景)
核心逻辑是把两个JSON的拼接点}{替换为数组元素分隔符},{,再在外层补上方括号,即可得到合法的JSON数组,正常解析后遍历取值即可。
JavaScript 示例代码
const output = "{\"response\":200,\"message\":\"Id: 123 updated successfully\"}{\"response\":403,\"message\":\"Receipt with Id: 124 not updated\"}"; // 转换为合法JSON数组字符串 const validJson = `[${output.replaceAll('}{', '},{')}]`; const resultList = JSON.parse(validJson); // 访问response参数 resultList.forEach(item => console.log(item.response)); // 依次输出200、403
Python 示例代码
import json output = '{"response":200,"message":"Id: 123 updated successfully"}{"response":403,"message":"Receipt with Id: 124 not updated"}' # 转换为合法JSON数组字符串 valid_json_str = f"[{output.replace('}{', '},{')}]" result_list = json.loads(valid_json_str) # 访问response参数 for item in result_list: print(item["response"]) # 依次输出200、403
方案2:正则匹配独立JSON(兼容性强,适合JSON内容含特殊字符的场景)
如果JSON内部的字符串字段本身包含}{字符,方案1的替换逻辑会出错,此时可以用正则匹配所有独立的{}包裹的JSON结构,逐个解析取值。
Python 示例代码
import re import json output = '{"response":200,"message":"Id: 123 updated successfully"}{"response":403,"message":"Receipt with Id: 124 not updated"}' # 匹配所有独立的JSON对象字符串 json_item_list = re.findall(r'\{[^{}]*\}', output) for json_str in json_item_list: item = json.loads(json_str) print(item["response"])
注意:如果JSON结构存在多层嵌套的
{},上述简单正则无法正确匹配,需使用专门的流式JSON解析工具处理。
内容的提问来源于stack exchange,提问作者K K
相关产品推荐
相关产品推荐

