如何将文本解析为 JSON 对象?

How do I parse text into a JSON object?

我有一个包含以下示例条目的 dhcp 租约文件:

lease 172.16.20.11 { starts 4 2014/10/09 18:33:57; ends 4 2014/10/09 18:43:57; cltt 4 2014/10/09 18:33:57; binding state active; next binding state free; rewind binding state free; hardware ethernet XX:XX:XX:XX:XX:XX; client-hostname "phone"; }

我正在尝试找到一种方法将信息转换为 JSON,以便我可以在 Dojo 中使用。

我希望输出像

{"leases": ["address":"172.16.20.11", "starts":"2014/10/09 18:33:57", "ends":"2014/10/09 18:43:57","
client-hostname":"phone"]}

有办法吗?

谢谢, 蒂姆 T

var str = 'lease 172.16.20.11 { starts 4 2014/10/09 18:33:57; ends 4 2014/10/09 18:43:57; cltt 4 2014/10/09 18:33:57; binding state active; next binding state free; rewind binding state free; hardware ethernet XX:XX:XX:XX:XX:XX; client-hostname "phone"; }';

var res = str.split(/[\s;]+/); // regex match spaces and semicolons

// Create your leases array with a lease object from the parsed string
var leases = {leases:[{
address: res[1],
starts: res[5] + " " + res[6],
ends: res[9] + res[10],
client_hostname: res[30].split('"')[1]
}]};

var json = JSON.stringify(leases); //convert the array of leases to json string

[编辑] 客户端主机名必须是 client_hostname 因为变量名限制

[编辑] 将租约更改为具有数组 属性 的对象,以更接近地匹配您想要的输出

[EDIT] 从 "phone" 解析 phone 为 client_hostname