最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Remove white space in Json - Stack Overflow

programmeradmin2浏览0评论

How can I remove white space in the following code block and store in a javascript variable?

This is original format

{ "info":"First Json",
  "description":"Official Website",
  "timestamp":"1337936081",
   "rates":{
            "USD":"840", 
            "CHF":"1319", 
            "BDT":"298",
            } 
}    

This is the format I want

{"info":"Central Bank of Myanmar","description":"Official Website of Central Bank of Myanmar","timestamp":"1337936081","rates":{"USD":"840","CHF":"1319","BDT":"298","SGD":"632","JPY":"1053","GBP":"887","AUD":"759"}}     

How can I remove white space in the following code block and store in a javascript variable?

This is original format

{ "info":"First Json",
  "description":"Official Website",
  "timestamp":"1337936081",
   "rates":{
            "USD":"840", 
            "CHF":"1319", 
            "BDT":"298",
            } 
}    

This is the format I want

{"info":"Central Bank of Myanmar","description":"Official Website of Central Bank of Myanmar","timestamp":"1337936081","rates":{"USD":"840","CHF":"1319","BDT":"298","SGD":"632","JPY":"1053","GBP":"887","AUD":"759"}}     
Share Improve this question asked Oct 31, 2014 at 15:41 Chit Min ThuChit Min Thu 1121 gold badge1 silver badge7 bronze badges 5
  • If you wanna store in a JS variable just assign that to a variable. It's as easy as that – Ciprian Mocanu Commented Oct 31, 2014 at 15:43
  • Why would you want to remove the white space? – Ciprian Mocanu Commented Oct 31, 2014 at 15:43
  • The code doesn't work if I don't remove the white space. – Chit Min Thu Commented Oct 31, 2014 at 15:44
  • @ChitMinThu Any good JSON parser should work whether the JSON is prettified or condensed. – Mike Brant Commented Oct 31, 2014 at 15:45
  • this is a valid question... why was it voted down? – quemeful Commented Oct 6, 2016 at 11:57
Add a ment  | 

2 Answers 2

Reset to default 11
var jsonWithWhitespaceRemoved = JSON.stringify(JSON.parse(variableWithJsonWhitespace))

Following is screenshot to better explain the above answer:

  1. open browser and press F12 to open console tab
  2. paste similar code as mentioned in below screenshot
  3. Run

We would get desired oute on the right hand side.

发布评论

评论列表(0)

  1. 暂无评论