Creating a JSON dynamically with each input value using jquery

后端 未结 4 495
逝去的感伤
逝去的感伤 2020-12-02 04:49

I got a situation where I would like to read some data off a JSON format through PHP, however I am having some issues understanding how I should construct the Javascript obj

相关标签:
4条回答
  • 2020-12-02 04:50

    same from above example - if you are just looking for json (not an array of object) just use

    function getJsonDetails() {
          item = {}
          item ["token1"] = token1val;
          item ["token2"] = token1val;
          return item;
    }
    console.log(JSON.stringify(getJsonDetails()))
    

    this output ll print as (a valid json)

    { 
       "token1":"samplevalue1",
       "token2":"samplevalue2"
    }
    
    0 讨论(0)
  • 2020-12-02 04:51

    Like this:

    function createJSON() {
        jsonObj = [];
        $("input[class=email]").each(function() {
    
            var id = $(this).attr("title");
            var email = $(this).val();
    
            item = {}
            item ["title"] = id;
            item ["email"] = email;
    
            jsonObj.push(item);
        });
    
        console.log(jsonObj);
    }
    

    Explanation

    You are looking for an array of objects. So, you create a blank array. Create an object for each input by using 'title' and 'email' as keys. Then you add each of the objects to the array.

    If you need a string, then do

    jsonString = JSON.stringify(jsonObj);
    

    Sample Output

    [{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}] 
    
    0 讨论(0)
  • 2020-12-02 04:51

    I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.

    Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.

    See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.

    In your case:

    var array = [];
    $("input[class=email]").each(function() {
        array.push({
            title: $(this).attr("title"),
            email: $(this).val()
        });
    });
    // then to get the JSON string
    var jsonString = JSON.stringify(array);
    
    0 讨论(0)
  • 2020-12-02 05:11

    May be this will help, I'd prefer pure JS wherever possible, it improves the performance drastically as you won't have lots of JQuery function calls.

    var obj = [];
    var elems = $("input[class=email]");
    
    for (i = 0; i < elems.length; i += 1) {
        var id = this.getAttribute('title');
        var email = this.value;
        tmp = {
            'title': id,
            'email': email
        };
    
        obj.push(tmp);
    }
    
    0 讨论(0)
提交回复
热议问题