jQuery:将带逗号分隔值的字符串转换为特定的JSON格式 [英] jQuery: Convert string with comma separated values to specific JSON format
问题描述
我一直在为一些可能微不足道的事情而浪费时间:
I've been losing hours over something that might be trivial:
我有一个逗号分隔的电子邮件地址列表,我想要转换到特定的JSON格式,与Mandrill API一起使用( https://mandrillapp.com /api/docs/messages.JSON.html )
I've got a list of comma-separated e-mail addresses that I want to convert to a specific JSON format, for use with the Mandrill API (https://mandrillapp.com/api/docs/messages.JSON.html)
我的字符串:
var to = 'bigbadwolf@grannysplace.com,hungry@hippos.com,youtalkin@to.me';
我认为需要的是:
[
{"email": "bigbadwolf@grannysplace.com"},
{"email": "hungry@hippos.com"},
{"email": "youtalkin@to.me"}
]
我有一个JSFiddle我几乎拥有它我想:
http:// jsfiddle .net / 5j8Z7 / 1 /
I've got a JSFiddle in which I almost have it I think: http://jsfiddle.net/5j8Z7/1/
我一直在研究几个jQuery插件,其中包括: http://code.google.com/p/jquery-json
但我不断收到语法错误。
I've been looking into several jQuery plugins, amongst which: http://code.google.com/p/jquery-json But I keep getting syntax errors.
关于SO的另一篇文章建议手工完成: JavaScript关联数组到JSON
Another post on SO suggested doing it by hand: JavaScript associative array to JSON
这可能是一个微不足道的问题,但Mandrill API的Codecadamy文档已经停止了一段时间没有合适的例子。
This might be a trivial question, but the Codecadamy documentation of the Mandrill API has been down for some time and there are no decent examples available.
推荐答案
var json = [];
var to = 'bigbadwolf@grannysplace.com,hungry@hippos.com,youtalkin@to.me';
var toSplit = to.split(",");
for (var i = 0; i < toSplit.length; i++) {
json.push({"email":toSplit[i]});
}
这篇关于jQuery:将带逗号分隔值的字符串转换为特定的JSON格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!