1234567891011121314151617181920212223242526272829303132333435363738394041424344 |
- /**
- *
- 结果是:
- {
- "keshi":"呼吸科",
- "user":{
- "name":""
- }
- }
- */
- export function extactAndParseJsonFromString(inputString:string){
- let startIndex = inputString.indexOf("{")
- if(startIndex==-1) return {}
- let count = 0;
- let endIndex = startIndex;
- // 遍历字符串,计算花括号实现数量平衡
- for (let i = startIndex; i < inputString.length; i++) {
- // console.log(i,inputString[i])
- if(inputString[i]==="{"){
- count++;
- }else if(inputString[i]==="}"){
- count--;
- }
- // 当花括号平衡,我们找到了完整的JSON
- if(count === 0){
- endIndex = i;
- break;
- }
- }
- // 若不平衡
- if(count!=0) return {};
- // 提取JSON字符串,并解析
- const jsonString = inputString.slice(startIndex,endIndex+1);
- console.log("jsonString",jsonString)
- try{
- return JSON.parse(jsonString);
- }catch(error){
- console.error("Failed to parse JSON",error);
- return {}
- }
- }
|