How to replace and correct json path string with r

2019-08-28 17:19发布

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

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

2条回答
Fickle 薄情
2楼-- · 2019-08-28 17:57
json.replace(/-/g, '.').replace(/(^|\.)([0-9]+)($|\.)/g, '[$2]$3');
  1. Replace the dashes with periods
  2. Search for all numbers within periods or at the beginning or end of a line. Surround those results with brackets. Then add the period ($3) after the bracket if necessary.
查看更多
等我变得足够好
3楼-- · 2019-08-28 18:04

You could do something like this:

str.replace(/([a-z]+)/gi, ".$1").replace(/(\d+)/gi, "[$1]").replace(/-/g, '');
查看更多
登录 后发表回答