how to insert text into json using jquery/javascript

This question already has an answer here:

  • Serializing to JSON in jQuery [duplicate] 11 answers

  • if u have a well formatted text string with comma separated numbers like this '123,456,789' and with that i mean no spaces or tabs then u can convert it simply into a javascript array.

    var myTextwithNuumbercodes='123,456,789';
    
    var numbercodes=myTextwithNuumbercodes.split(',');
    

    returns ['123','456','789']

    if u have a JSON string like this '[123,456,789]' then u get a javascript array by calling JSON.parse(theJSONString)

    var numbercodes=JSON.parse('[123,456,789]');
    

    returns [123,456,789]

    notice the "[]" in the string ... that is how u pass a JSON array toconvert it back to a string u can use JSON.stringify(numbercodes);

    if u have a total messed up text then it's hard to convert it into a javascript array but u can try with something like that

    var numbercodes='123, 456, 789'.replace(/s+/g,'').split(',');
    

    this firstly removes the spaces between the numbers and commas and then splits it into a javascript array

    in the first and last case u get a array of strings u can transform this strings into numbers by simply adding a + infront of them if u call them like

    mynumbercode0=(+numbercodes[0]);// () not needed here ...
    

    in the 2nd case u get numbers

    if u want to convert an array to a string u can also use join();

    [123,456,789].join(', ');
    

    假设你的数据是一个字符串,然后用逗号分隔,在for循环中使用parseInt将字符串数字转换为实际的数字并删除空白,然后JSON.stringify转换为JSON。


    You could use .push() push values at the end of an array. After that you could use JSON.stringify(nuumbercodes) to make a JSON string representation of your Array.

    链接地址: http://www.djcxy.com/p/8084.html

    上一篇: 如何从JSON对象构建JSON字符串

    下一篇: 如何使用jquery / javascript将文本插入到json中