在JSON stringfy之后从字符串中删除括号和双引号

时间:2018-03-01 06:10:43

标签: jquery arrays json ajax

我想将数据发送到API,所以我将数组传递给ajax请求。首先我做了JSON.stringfy()

var string = JSON.stringify(Allsubjects);
//string = "["Mathmatics","English","Hindi","Science","Social Science"]"

注意:在字符串化之后,它会在paranthises之前和之后添加额外的双引号

我希望输出如下:

Mathmatics,English,Science 

没有任何双重引号,Paranthises和单引号。

需要发送数据:

data: { classes_sections:"{'2':['E']}",
        subjects:"{'data':['Science','English','Maths','Others']}"
       },

API结构

 "E": { "subject": [   "Science",
                        "English",
                        "Maths",
                        "Others"
                    ]
       },

1 个答案:

答案 0 :(得分:0)

您应该使用join代替stringify

var Allsubjects = ["Mathmatics","English","Hindi","Science","Social Science"];
var string = Allsubjects.join(",");

console.log( string );

如果您将json字符串传递给API,您可以:

var Allsubjects = ["Mathmatics", "English", "Hindi", "Science", "Social Science"];
var classes_sections = ["E"];
var class = "2";

data: {
    classes_sections:'{"' + class + '":' + JSON.stringify(classes_sections) + '}',
    subjects: '{"data":' + JSON.stringify(Allsubjects) + '}'
},

或者您可以构建JSON

var Allsubjects = ["Mathmatics", "English", "Hindi", "Science", "Social Science"];
var classes_sections = ["E"];
var className = "2";

//Structure JSON
var subjectJSON = { data : Allsubjects };
var classJSON = {};
classJSON[ className ] = classes_sections;

data: {
    classes_sections: JSON.stringify( classJSON ),
    subjects: JSON.stringify( subjectJSON )
},

Doc:join