How to create JSON string in JavaScript?

前端 未结 7 1790
借酒劲吻你
借酒劲吻你 2020-12-23 02:31
window.onload = function(){
    var obj = \'{
            \"name\" : \"Raj\",
            \"age\"  : 32,
            \"married\" : false
            }\';

    var va         


        
相关标签:
7条回答
  • 2020-12-23 03:06

    The way i do it is:

       var obj = new Object();
       obj.name = "Raj";
       obj.age  = 32;
       obj.married = false;
       var jsonString= JSON.stringify(obj);
    

    I guess this way can reduce chances for errors.

    0 讨论(0)
  • 2020-12-23 03:06

    Use JSON.stringify:

    > JSON.stringify({ asd: 'bla' });
    '{"asd":"bla"}'
    
    0 讨论(0)
  • 2020-12-23 03:06

    json strings can't have line breaks in them. You'd have to make it all one line: {"key":"val","key2":"val2",etc....}.

    But don't generate JSON strings yourself. There's plenty of libraries that do it for you, the biggest of which is jquery.

    0 讨论(0)
  • 2020-12-23 03:19

    This can be pretty easy and simple

    var obj = new Object();
    obj.name = "Raj";
    obj.age = 32;
    obj.married = false;
    
    //convert object to json string
    var string = JSON.stringify(obj);
    
    //convert string to Json Object
    console.log(JSON.parse(string)); // this is your requirement.
    
    0 讨论(0)
  • 2020-12-23 03:19

    I think this way helps you...

    var name=[];
    var age=[];
    name.push('sulfikar');
    age.push('24');
    var ent={};
    for(var i=0;i<name.length;i++)
    {
    ent.name=name[i];
    ent.age=age[i];
    }
    JSON.Stringify(ent);
    
    0 讨论(0)
  • 2020-12-23 03:22

    Javascript doesn't handle Strings over multiple lines.

    You will need to concatenate those:

    var obj = '{'
           +'"name" : "Raj",'
           +'"age"  : 32,'
           +'"married" : false'
           +'}';
    

    You can also use template literals in ES6 and above: (See here for the documentation)

    var obj = `{
               "name" : "Raj",
               "age" : 32,
               "married" : false,
               }`;
    
    0 讨论(0)
提交回复
热议问题