2017-06-21 45 views
-3

獲取一些服務器,我得到一個GET請求作爲響應之後:解析JavaScript代碼爲響應

variable1 = ["something", ["a","b","c"], ["more stuff"]] 

我需要提取variable1[1]陣列["a","b","c"]在我的js代碼中使用。

(我用的的NodeJS的要求 - 這是一個服務器端的請求,這是我無法控制的外部Web服務)

+3

很酷。你有什麼嘗試?你卡在哪裏?你熟悉'JSON.parse'和'String.prototype.split'嗎? –

+0

什麼?我不明白... – Ionut

+0

我認爲這應該是JSON ...所以如果是這樣,請閱讀如何使用它。 – CBroe

回答

2

我假設你的返回值是包含完整表達一個字符串。

假設你有這樣的一個字符串:

'variable1 = ["something", ["a","b","c"], ["more stuff"]]'

,並要恢復variable1[1]含義:["a","b","c"]

您可以通過=分割字符串,然後用JSON.parse()解析它,隨後通過查詢它對於期望的索引[1]如下所示:

var x = 'variable1 = ["something", ["a","b","c"], ["more stuff"]]'; 
 
var y = JSON.parse(x.split('=')[1])[1]; 
 

 
console.log(y);

正如你已經接受了答案,我將離開下面的解決方案 中,但會建議以上。

你也可以創建一個新的功能,並返回表達式的結果,與此類似:

var x = 'variable1 = ["something", ["a","b","c"], ["more stuff"]]'; 

var y = new Function('return ' + x); 

然後,您可以返回你想要什麼相似獲得variable1[1]

警告
New Function()呈現可能與eval()相同的風險,特別是如果檢索expressi如果您無法控制來自第三方服務的JSON字符串中的內容,您是否可能會在不知情的情況下執行惡意代碼?

var x = 'variable1 = ["something", ["a","b","c"], ["more stuff"]]'; 
 

 
console.log(new Function('return ' + x)()[1]);

+0

你真棒!比你:) :) – Mike

+3

@Mike Word的警告雖然 - 如果'新功能()'提出了與'eval()'相同的問題,它可能是不安全的,因爲你可能會不知情的情況下執行惡意代碼。 – Nope

+0

@Fran這就是爲什麼分割'='和'JSON.parse'表達式會更好。 –

0

如果您想獲得該表達式的值的一個更安全的方式,考慮對第一=然後在表達做JSON.parse分裂的結果。

const input = 'variable1 = ["something", ["a","b","c"], ["more stuff"]]'; 
 
const expression = input 
 
    // Split the string on the equals sign 
 
    .split('=') 
 
    // Gather the pieces after the first one (just in case there's a "=" in the array) 
 
    .slice(1) 
 
    // Put it back together into a single string 
 
    .join(''); 
 
    
 
// Convert the string to an actual array 
 
const output = JSON.parse(expression); 
 
console.log(output);

這種方法完全避免了Functioneval,和相關方法的安全問題。