0

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 Answers 2

1
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.
Sign up to request clarification or add additional context in comments.

4 Comments

beautiful regex, could use some explanation for those not very familiar with regexes though
Yeah sorry, I got dragged away from my computer temporarily.
i ran the code, that was almost there, its missing a '.' after ']' .. it should be [55].fathers[2].married not [55]fathers[2]married
Right you are. Didn't notice that. Updated.
0

You could do something like this:

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

1 Comment

did not work when a field had a number between it. Ex: "55-multivalorado-1-data45-0" became ->> "[55].multivalorado[1].data[45][0]"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.