我有一个字符串的javascript数组,只有修改过的json路径,如下所示:
55-fathers-2-married
55-fathers-2-name
55-fathers-2-sons
55-fathers-1-id
55-fathers-1-married
55-fathers-1-name
55-fathers-1-daughters2-2-age
55-fathers-1-daughters2-2-name
55-fathers-1-daughters2-1-age
55-fathers-1-daughters2-1-name
55-fathers-1-daughters2-0-age
55-fathers-1-daughters2-0-name
55-fathers-1-sons-0
55-fathers-1-sons-1
55-fathers-1-sons-2
55-fathers-0-id-somethingelse
如何更改此列表中的所有元素,以成为有效的json路径?我的意思是这样的:
[55].fathers[2].married
[55].fathers[2].name
[55].fathers[2].sons
[55].fathers[1].id
[55].fathers[1].married
[55].fathers[1].name
[55].fathers[1].daughters2[2].age
[55].fathers[1].daughters2[2].name
[55].fathers[1].daughters2[1].age
[55].fathers[1].daughters2[1].name
[55].fathers[1].daughters2[0].age
[55].fathers[1].daughters2[0].name
[55].fathers[1].sons[0]
[55].fathers[1].sons[1]
[55].fathers[1].sons[2]
[55].fathers[0].id.somethingelse
答案 0 :(得分:1)
json.replace(/-/g, '.').replace(/(^|\.)([0-9]+)($|\.)/g, '[$2]$3');
答案 1 :(得分:0)
你可以这样做:
str.replace(/([a-z]+)/gi, ".$1").replace(/(\d+)/gi, "[$1]").replace(/-/g, '');