I have this string :
const string = "{* * @test * { * username: {{username}} * email: {{email}} * password: {{password}} * name: { * first: {{firstname}} * last: {{lastname}} * }, * phone: {{phone}} * } }"
and i want in the end to have something like this :
{
"username": "{{username}}",
"email": "{{email}}",
"password": "{{password}}",
"name": {
"first": "{{firstname}}",
"last": "{{lastname}}"
},
"phone": "{{phone}}"
}
Here is my code :
const str = "{* * @test * { * username: {{username}} * email: {{email}} * password: {{password}} * name: { * first: {{firstname}} * last: {{lastname}} * }, * phone: {{phone}} * } }"
const regex = /.* \{ \* ([^:]+): ([^ ]+) \* } }/gm;
const subst = `{\n\t"1ドル": "2ドル"\n}`;
// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);
console.log(result);
mooga
3,3274 gold badges25 silver badges40 bronze badges
asked Mar 16, 2019 at 20:45
1 Answer 1
One approach is to replace all of your invalid JSON tokens to produce a valid JSON string and use JSON.parse
to parse the JSON string into an object.
This is rather ham-fisted as shown and likely needs to be tweaked and optimized if you have additional edge cases in your actual data, but should handle the recursive structural problem nicely. Treat it as a proof-of-concept.
const string = "{* * @test * { * username: {{username}} * email: {{email}} * password: {{password}} * name: { * first: {{firstname}} * last: {{lastname}} * }, * phone: {{phone}} * } }";
const cleaned = string
.replace(/({{.+?}})/g, `"1ドル"`) // quote the template variables
.replace(/ \* ([a-z]+?): /ig, ` "1ドル": `) // quote the keys
.replace(/" "/g, `","`) // add commas between keys
.replace(/\*/g, "") // remove asterisks
.replace(/@[a-z]+/ig, "") // get rid of the `@test`
.trim() // trim so we can rip off the `{}`s
;
const parsed = JSON.parse(cleaned.substr(1, cleaned.length - 2));
const expected = {
"username": "{{username}}",
"email": "{{email}}",
"password": "{{password}}",
"name": {
"first": "{{firstname}}",
"last": "{{lastname}}"
},
"phone": "{{phone}}"
};
console.log(
`matches expected? ${JSON.stringify(expected) === JSON.stringify(parsed)}\n`,
parsed
);
answered Mar 16, 2019 at 21:14
Sign up to request clarification or add additional context in comments.
Comments
lang-js