如何用正则表达式替换和纠正json路径字符串?

时间:2013-07-22 19:55:32

标签: javascript regex json jsonpath

我有一个字符串的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

2 个答案:

答案 0 :(得分:1)

json.replace(/-/g, '.').replace(/(^|\.)([0-9]+)($|\.)/g, '[$2]$3');
  1. 用句号替换短划线
  2. 搜索句点内或行的开头或结尾处的所有数字。用括号括起这些结果。然后在必要时在括号后添加句点($ 3)。

答案 1 :(得分:0)

你可以这样做:

str.replace(/([a-z]+)/gi, ".$1").replace(/(\d+)/gi, "[$1]").replace(/-/g, '');