[英]How to parse an unusual array?
我正在使用“ cordova-brother-label-printer ” cordova插件來獲取打印機列表。 findNetworkPrinters
函數將返回數據,如下所示:
[{nodeName=PrinterName123456, serNo=Serial12345, ipAddress=192.168.1.134, macAddress=MA:CA:DD:RE:SS}]
這不是標准的JSON編碼字符串,因此我無法使用JSON.parse對其進行解析。 還有另一種方法可以將其轉換為JSON嗎?
謝謝你的幫助。
使用帶有RegExp的String.replace()
將字符串重新格式化為JSON格式,然后使用JSON.parse()
解析:
const str = '[{nodeName=PrinterName123456, serNo=Serial12345, ipAddress=192.168.1.134, macAddress=MA:CA:DD:RE:SS}]'; const json = str .replace(/([^\\[\\]{}=\\s,]+)/g, '"$1"') .replace(/=/g, ':'); console.log(JSON.parse(json));
您可以更換
{
與{"
}
與"}
,\\s*
和","
=
與":"
按此順序創建一個有效的JSON字符串,然后進行解析。
var input = "[{nodeName=PrinterName123456, serNo=Serial12345, ipAddress=192.168.1.134, macAddress=MA:CA:DD:RE:SS}]"; var output = JSON.parse( input.replace(/{/g,'{"') .replace(/}/g, '"}') .replace(/,\\s*/g, '","') .replace(/=/g, '":"') ); console.log(output);
使用javascript的replace
函數,您應該可以將其轉換為有效的JSON。
嘗試這個:
var inputString = '[{nodeName=PrinterName123456, serNo=Serial12345, ipAddress=192.168.1.134, macAddress=MA:CA:DD:RE:SS}]';
var json = JSON.parse(inputString.replace(/([^={]*)=([^,}]*)(,\s?)?/g, '"$1": "$2"$3'));
正則表達式: https : //regex101.com/r/AMCNlh/1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.