0

Hi All I want to fix my json I got strings without " and I need to bring them back somehow I have found a regex that find some of the texts but still its not returning the right result

 var newString2 = j.replace(/[a-zA-Z0-9@.,_+]*[^:][\w]/g, function(x){
      return '"'+x+'"';

    });

my json

{
  User_Story_UI_24: 
   {
     Env:Staging,
     UserName:[email protected],
     Password: User@SDF45sdfg,
     Supplier:Xxxxx,
     SupplierWebSite:www.xxxx.com,
     SupplierPhone:+111 2223334440,
     SupplierAddress:sss asf21, asf asf, saf
   }
}

the epcepted result

{
  "User_Story_UI_24": 
   {
     "Env":"Staging",
     "UserName":"[email protected]",
     "Password": "User@SDF45sdfg",
     "Supplier":"Xxxxx",
     "SupplierWebSite":"www.xxxx.com",
     "SupplierPhone":"+111 2223334440",
     "SupplierAddress":"sss asf21, asf asf, saf"
   }
}
6
  • 3
    What is the expected result? Commented Jul 18, 2019 at 12:03
  • @mrzasa I think the values under User_Story_UI_24 should be within single or double quotes, is what I understood Commented Jul 18, 2019 at 12:06
  • Where are you seeing this JSON? How is it created / sent? "Fixing a JSON" just seems like a bad idea. Commented Jul 18, 2019 at 12:08
  • One doesn't just find a regular expression Commented Jul 18, 2019 at 12:09
  • I can't fix the string its cam from groovy pipeline on jenkins as a parameter Commented Jul 18, 2019 at 12:09

1 Answer 1

1

I've used a regex that detects the lines in your regex (assuming it's in the same format as in your example).
Then it uses a function that receives the matching groups as its parameters and creates two quoted strings accordingly.

The only change I made to your input was adding a comma after the last property, to keep all the lines in the same format:

const input = `{
  User_Story_UI_24: 
   {
     Env:Staging,
     UserName:[email protected],
     Password: User@SDF45sdfg,
     Supplier:Xxxxx,
     SupplierWebSite:www.xxxx.com,
     SupplierPhone:+111 2223334440,
     SupplierAddress:sss asf21, asf asf, saf,
   }
}`;

let ans = input.replace(/(\w+?): ?([+\w @.,]+),/g, (row, prop, value) => {
  return `"${prop}": "${value}",`;
});
console.log(ans);

Sign up to request clarification or add additional context in comments.

3 Comments

ammm almost what about the User_Story_UI?
I'm afraid it has to be modified using a separate regex, as it doesn't follow the same format and therefore the replacing function will be missing a parameter. BTW the JSON is valid without properties being wrapped in quotes
need to erase the comma in the last parameter

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.