网站首页 > 知识剖析 正文
从JavaScript中的字符串中提取JSON可以使用以下几种方法:
- 使用JSON.parse()方法:JSON.parse()方法可以将一个符合JSON格式的字符串转换为JavaScript对象。通过将字符串作为参数传递给JSON.parse()方法,可以将其转换为对应的JavaScript对象。例如:
var jsonString = '{"name":"John", "age":30, "city":"New York"}';
var jsonObj = JSON.parse(jsonString); console.log(jsonObj);
输出结果为:
{ name: 'John', age: 30, city: 'New York' }
- 使用正则表达式:如果字符串中包含多个JSON对象,可以使用正则表达式来提取每个JSON对象。例如,假设字符串中包含多个JSON对象,可以使用以下代码提取每个JSON对象:
var jsonString = '{"name":"John", "age":30, "city":"New York"} Some other text {"name":"Jane", "age":25, "city":"London"}';
var regex = /{[^{}]+}/g;
var jsonObjects = jsonString.match(regex);
console.log(jsonObjects);
- 使用第三方库:除了上述方法,还可以使用一些第三方库来提取JSON。例如,使用lodash库的_.attempt()方法可以安全地解析JSON字符串,即使字符串不符合JSON格式也不会抛出错误。以下是使用lodash库的示例代码:
var _ = require('lodash');
var jsonString = '{"name":"John", "age":30, "city":"New York"}';
var jsonObj = _.attempt(JSON.parse.bind(null, jsonString));
console.log(jsonObj);
- 上一篇: 10分钟让你明白JSON是什么
- 下一篇: param的类型转化(parse,serialize等)
猜你喜欢
- 2024-11-18 深入了解:JSON.stringify的不可思议之处
- 2024-11-18 你不知道的JavaScript中的5个JSON秘密功能
- 2024-11-18 从业二十年的测试工程师今天给大家分享postman的使用技巧
- 2024-11-18 手把手教你JSON解析完Cube数据,如何输出到Excel
- 2024-11-18 「jQuery-5」 JavaScript对象和json
- 2024-11-18 亲手带你 Debug Fastjson 的安全漏洞
- 2024-11-18 JSON数据格式
- 2024-11-18 你不知道的JSON.stringify神操
- 2024-11-18 JSON如何解析
- 2024-11-18 38.JavaScript:try...catch异常处理
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)