我无法以下列格式创建Json字符串,请帮忙。其中键值对可以是数字:
"tag_container": { "tag1": "Tag1", "tag2": "Tag2", ..... }
var uploaded = new Uploaded();
var str = "*#Hello* i *#am* writing a regexp *#h*";
var re = hash_parser(str);
uploaded.tag_list = new Array;
uploaded.tag_list.tag = new Array;
for(var i = 0; i < re.length; i++)
{
uploaded.tag_list[i] = new Object;
uploaded.tag_list[i].**tag** = re[i];
}
以上代码的格式如下:
"tag_list":[{"**tag**":"*#Hello*"},{"**tag**":"*#am*"},{"**tag**":"*#h*"}]
答案 0 :(得分:3)
我认为也许你可能会将JSON与对象文字语法混淆。
而不是:
"tag_container": { "tag1": "Tag1", "tag2": "Tag2", ..... }
你应该使用普通的JS语法:
var tag_container = { "tag1": "Tag1", "tag2": "Tag2", ..... }
...但是很难从你的帖子中说出来。如果你认识任何可以帮助你学习英语的人,那么我(以及其他人)可以更好地理解这个问题。
答案 1 :(得分:0)
将内容转换为JSON的最简单方法是使用JSON.stringify
。
var jsonString = JSON.stringify({ tag_container: { tag1: 'tag1', tag2: 'tag2' }});
stringify在所有现代浏览器中都可用。如果您希望支持旧版本,JSON2 library可能是最佳选择,因为它提供与官方JSON规范相同的API。
答案 2 :(得分:0)
我认为你要做的是这样的事情:
var reLen = re.length;
uploaded.tag_list = {};
for(var i = 0; i < reLen; i++)
{
uploaded.tag_list['tag' + (i+1)] = re[i];
}
这将输出您希望看到的格式,即
'"tag_container": {"tag1": "*#Hello*", "tag2": "*#am*", "tag3": "*#h*"}'
答案 3 :(得分:-1)
谢谢大家的回复和指导我的问题以其他方式解决了我将json字符串发送到跨域
string = "hi @group1 @group2 *user1 *user2 #fs #ffsd #fsdf";
并生成了json字符串
{"raw_msg":"hi @group1 @group2 *user1 *user2 #fs #ffsd #fsdf","msg_type":"group","top_msg_id":0,"file_container":{"file1":{"id":"","file_name":"","uri":""},"file2":{"id":"","file_name":"","uri":""}},***"tag_list":["fs","ffsd","fsdf"]***,"link_list":"","image_container":{"image1":{"id":"","name":"Name","uri":""},"image2":{"id":"","name":"Name","uri":""}},"attached_thread":{"thread1":{"title":"","top_id":"","last_id":""},"thread2":{"title":"","top_id":"","last_id":""}},"to_user":["user1","user2"],"to_group":["group1","group2"]}