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

Javascript 如何用正则表达式替换和更正json路径字符串?,javascript,regex,json,jsonpath,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-fathe

我有一个字符串的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
  • 将破折号替换为句点
  • 搜索句点内或行首或行尾的所有数字。将这些结果用括号括起来。如有必要,在括号后加上句号($3)

  • 你可以这样做:

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

    漂亮的正则表达式,可以为那些不太熟悉正则表达式的人做一些解释。是的,对不起,我暂时被从我的计算机上拖走了。我运行了代码,代码就在那里,在“]”之后缺少“.”。。应该是[55]父亲[2]已婚而不是[55]父亲[2]结婚。我没注意到。更新。当字段之间有数字时,该字段不起作用。例如:“55-multiflorado-1-data45-0”变为->“[55]。multiflorado[1]。数据[45][0]”
    str.replace(/([a-z]+)/gi, ".$1").replace(/(\d+)/gi, "[$1]").replace(/-/g, '');