Hello so I'm trying to clean a json string that i have for example:
" .tagline-wrapper ":{
" padding-top":"398px",
" font-size":" 1.8rem",
" "
},
".tagline ":{
" padding-top":"398px",
" font-size":" 1.8rem",
" ",
},
".wrapper":{
" padding-top":"398px",
" font-size":" 1.8rem",
""
},
I need to remove the double quotes that are empty or with white space it could have multiple white space, i tried to remove consecutive white space and then replace the quotes as so:
str = str .replace("\" \"",'');
str = str .replace("\"\"",'');
but nothing works, i should also remove the comma but i guess i can remove consecutive commas ignoring white space but if you can help with that too that would be great. The output that i need is:
" .tagline-wrapper":{
" padding-top":"398px",
" font-size":" 1.8rem",
},
".tagline":{
" padding-top":"398px",
"font-size":" 1.8rem",
},
".wrapper":{
" padding-top":"398px",
" font-size":" 1.8rem",
},
so that i can parse the json
Why not use regex to search for a "
followed by any number of whitespace followed by a "
" followed by an optional comma?
const str = ` ".tagline-wrapper ":{ " padding-top":"398px", " font-size":" 1.8rem", " " }, ".tagline ":{ " padding-top":"398px", " font-size":" 1.8rem", " ", }, ".wrapper":{ " padding-top":"398px", " font-size":" 1.8rem", "" },`; console.log(str.replace(/"\s*",?/g, ''))
I clean your string and try to apply JSON.parse to convert it to an object.
Noted : replaceAll is available in Nodejs 15.x.
const str = `".tagline-wrapper ":{ " padding-top":"398px", " font-size":" 1.8rem", " " }, ".tagline ":{ " padding-top":"398px", " font-size":" 1.8rem", " ", }, ".wrapper":{ " padding-top":"398px", " font-size":" 1.8rem", "" },`; const cleanStr = "{" + str.replaceAll('" ', '"').replaceAll(' "', '"').replaceAll('""', "").replaceAll(",\n,", ",\n").replaceAll(",\n\n}", "}").replaceAll(",\n \n}", "}").slice(0, -1) + "}"; console.log(cleanStr); const object = JSON.parse(cleanStr); console.log(object);
Try this code it may help you
function convertJSON(string) { string = string.replaceAll('"', "'"); string = string.replaceAll(/(\n\s*)/g, ''); string = string.replaceAll(/(,?\n?\s?'\s*',?)/g, ""); string = string.replaceAll(/},$/g, "}").replaceAll("'", '"'); let parsedJSON = null; try{ parsedJSON = JSON.parse(`{${string}}`); } catch{ console.log(string); } return parsedJSON; } let str = `".tagline-wrapper ":{ " padding-top":"398px", " font-size":" 1.8rem", " " }, ".tagline ":{ " padding-top":"398px", " font-size":" 1.8rem", " ", }, ".wrapper":{ " padding-top":"398px", " font-size":" 1.8rem", "" },`; console.log(convertJSON(str))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.