如何在json对象的每个索引中添加双引号

时间:2014-11-11 09:49:02

标签: javascript json node.js

要将(发送数据)连接到SMS API服务,我需要将我的数据转换为网站可以理解的内容。(他们的API无法接收标准jsons)

例如,我有一个像这样的对象:

var data = {
    message: ['hi', 'hello'],
    receptor: ['12345678', '87654321'],
    sender: ['1000' , '2000']
}

我需要把它转换成这样的东西:

{
    message: "['hi', 'hello']",
    receptor: "['12345678', '87654321']",
    sender: "['1000' , '2000']"
}

我写了一个简单的代码来转换它:

for( var index in data ){
    new_data[index] =  "["+ data[index]  ;
    for( var j in data[index] ){
        new_data[index][j] = '"' + data[index][j] + '"';
    }
    new_data[index] += "]";
}

但是数组中的单引号被删除并返回:

{
    message: "[hi, hello]",
    receptor: "[12345678, 87654321]",
    sender: "[1000 , 2000]"
}

我该怎么做?

我知道将它们转换为字符串并使用它可以解决问题,但我希望我能找到更好的方法。

2 个答案:

答案 0 :(得分:0)

var data = {
    message: ['hi', 'hello'],
    receptor: ['12345678', '87654321'],
    sender: ['1000' , '2000']
}

for(key in data){
    data[key] = '[\'' + data[key].join("','") + '\']';
}
//output
{
message: "['hi','hello']", 
receptor: "['12345678','87654321']", 
sender: "['1000','2000']"
}

for(key in data){
    data[key] = '"[\'' + data[key].join("','") + '\']"';
}
//output
{
message: ""['hi','hello']"", 
receptor: ""['12345678','87654321']"", 
sender: ""['1000','2000']""
}

for(key in data){
    data[key] = JSON.stringify(data[key]);
}
//output
{
message: "["hi","hello"]", 
receptor: "["12345678","87654321"]", 
sender: "["1000","2000"]"
}

答案 1 :(得分:-1)

var new_data = JSON.parse(data); 会打印出你要求的内容