如何用正则表达式替换和更正json路径字符串? [英] How to replace and correct json path string with regex?
本文介绍了如何用正则表达式替换和更正json路径字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个由字符串组成的javascript数组,只是修改了json路径,如下所示:
I have a javascript array of strings, with modified json path just, like this:
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路径?我的意思是这样的:
How can i change all elements from this list, to become a valid json path ? I mean something like this :
[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.replace(/-/g, '.').replace(/(^|\.)([0-9]+)($|\.)/g, '[$2]$3');
- 用点号代替破折号
- 搜索句点内或行首或行尾的所有数字.用括号将这些结果括起来.然后,如有必要,在括号后加上句点($ 3).
这篇关于如何用正则表达式替换和更正json路径字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文