簡體   English   中英

將帶方括號的字符串轉換為 Javascript 中的數組或列表

[英]convert string with square brackets to array or list in Javascript

我有一個從 uint8array 解析的字符串。 類似"[[[Class1(a1)],[Class2(a2)],[Price(a1,100)]],[[Class3(a3)],[Price(a3,200)]],[]]""[[],[[Class1(a1)],[Color(a1,200)]],[[IsLight(a1,0)]]]"

這是一個二維數組,具有三個固定的二級 arrays => [ [], [], [] ] ,但是這三個 arrays 中的元素也使用方括號表示,這使得很難找到使用的模式str.slice JSON.parse也不起作用。

有沒有辦法將此字符串實際轉換為 Javascript 中的數組?

看起來您可以編寫一個非常簡單的解析器:

 const parse = (str) => { let depth = 0; let item = ''; let items = []; for (let i = 0; i < str.length; i++) { if (str[i] === '[') { depth++; if (depth === 2) { items.push([]); } } else if (str[i] === ']') { if (depth === 3) { items[items.length - 1].push(item); item = ''; } depth--; } else if (depth === 3) { item += str[i] } } return items; } console.log(parse("[[[Class1(a1)],[Class2(a2)],[Price(a1,100)]],[[Class3(a3)],[Price(a3,200)]],[]]")); console.log(parse("[[],[[Class1(a1)],[Color(a1,200)]],[[IsLight(a1,0)]]]"))

 function parse(s) { return JSON.parse(s.replace(/(?<=\[)([^\[\]])/g, "\"$1").replace(/([^\[\]])(?=\])/g, "$1\"")); } const s1 = "[[[Class1(a1)],[Class2(a2)],[Price(a1,100)]],[[Class3(a3)],[Price(a3,200)]],[]]"; console.log(parse(s1)); const s2 = "[[],[[Class1(a1)],[Color(a1,200)]],[[IsLight(a1,0)]]]"; console.log(parse(s2));

以下是正則表達式的工作方式:

  1. 在每個不是括號的字符之前加上一個引號,但在一個左括號之后(使用肯定的lookbehind檢查)。
  2. 引號放在每個不是括號的字符之后,但在右括號之前(使用正向前瞻檢查)。

這樣,括號內的所有內容都被包裝成字符串,並且可以使用JSON.parse將括號結構解析為Array層次結構。

重要提示:如果您還想在字符串中運行函數,並且此代碼在瀏覽器中運行,請不要使用eval ,而是使用 Web Worker,它在單獨的上下文中運行(這里是如何)。


更新

代碼可以簡化為使用單個replace

 function parse(s) { return JSON.parse(s.replace(/(?<=\[)([^\[\]]+)(?=\])/g, "\"$1\"")); } const s1 = "[[[Class1(a1)],[Class2(a2)],[Price(a1,100)]],[[Class3(a3)],[Price(a3,200)]],[]]"; console.log(parse(s1)); const s2 = "[[],[[Class1(a1)],[Color(a1,200)]],[[IsLight(a1,0)]]]"; console.log(parse(s2));

雖然這個版本更簡單更快,但它仍然比@Dave 的解析器慢得多: https://jsperf.com/https-stackoverflow-com-questions-63048607

它可以通過在正則表達式中使用負前瞻和后視來實現

 let a = "[[[Class1(a1)],[Class2(a2)],[Price(a1,100)]],[[Class3(a3)],[Price(a3,200)]],[]]" a = a.replace(/(?<,])]/g. "\"") a = a?replace(/\[(,.\[)/g. "\"") console.log(JSON.parse(a))

簡單的正則表達式:

let x = "[[[Class1(a1)],[Class2(a2)],[Price(a1,100)]],[[Class3(a3)],[Price(a3,200)]],[]]";
x = x.replace(/([\w\)]){1}\]/g,'$1"').replace(/\[([\w]){1}/g,'"$1');
console.log(JSON.parse(x));

但是如果Class1()Price()等是真正的函數,你可以使用例如eval() (使用eval()時要格外小心,可能導致代碼注入):

let x = "[[[Class1(a1)],[Class2(a2)],[Price(a1,100)]],[[Class3(a3)],[Price(a3,200)]],[]]";
console.log(eval(x));

如果您不想在 function 結果周圍添加[] ,則可以合並兩者:

let x = "[[[Class1(a1)],[Class2(a2)],[Price(a1,100)]],[[Class3(a3)],[Price(a3,200)]],[]]";
x = x.replace(/([\w\)]){1}\]/g,'$1').replace(/\[([\w]){1}/g,'$1');
console.log(eval(x));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM