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

jquery - Convert comma separated list into JSON using Javascript - Stack Overflow

programmeradmin2浏览0评论

How do you convert a ma separated list into json using Javascript / jQuery?

e.g.

Convert the following:

var names = "Mark,Matthew,Luke,John,";

into:

var jsonified = {
    names: [
      {name: "Mark"},
      {name: "Mattew"},
      {name: "Luke"},
      {name: "John"}
    ]
  };

How do you convert a ma separated list into json using Javascript / jQuery?

e.g.

Convert the following:

var names = "Mark,Matthew,Luke,John,";

into:

var jsonified = {
    names: [
      {name: "Mark"},
      {name: "Mattew"},
      {name: "Luke"},
      {name: "John"}
    ]
  };
Share edited Sep 19, 2014 at 23:59 BenMorel 36.7k52 gold badges205 silver badges337 bronze badges asked May 4, 2012 at 1:16 Mike MikeMike Mike 1,1353 gold badges14 silver badges19 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 15
var jsonfied = {
    names: names.replace( /,$/, "" ).split(",").map(function(name) {
        return {name: name};
    })
};

result of stringfying jsonfied:

JSON.stringify( jsonfied );

{
    "names": [{
        "name": "Mark"
    }, {
        "name": "Matthew"
    }, {
        "name": "Luke"
    }, {
        "name": "John"
    }]
}

Live DEMO

发布评论

评论列表(0)

  1. 暂无评论