help with JSON

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • SirCodesALot

    help with JSON

    Hi All,

    Is it possible to create an JSON object from a string? For example

    var myArray = new Array(10)

    for (var i=0;i<10;i++)
    {
    myArray.push("{ idx:"+i+",val:" +i+"}");
    }

    var myStrObj = "[" + myArray.join(", ") + "]";

    var options = {"val1": "test",
    "val2" : myStrObj}

    I would like val2 to be an array of the values from myArray. is this
    possible, or do i have to break it out manually?

    Thanks in advance for your suggestions.
    -Scott
  • Peter Michaux

    #2
    Re: help with JSON

    On Jun 24, 9:02 am, SirCodesALot <sjour...@gmail .comwrote:
    Hi All,
    >
    Is it possible to create an JSON object from a string? For example
    >
    var myArray = new Array(10)
    >
    for (var i=0;i<10;i++)
    {
    myArray.push("{ idx:"+i+",val:" +i+"}");
    >
    }
    >
    var myStrObj = "[" + myArray.join(", ") + "]";
    >
    var options = {"val1": "test",
    "val2" : myStrObj}
    >
    I would like val2 to be an array of the values from myArray. is this
    possible, or do i have to break it out manually?
    Hand building JSON is really not a great idea. It is very error
    prone.. It is better to build up a JavaScript object and then use a
    JSON dumper function



    var options = {val1:"test", val2:[{idx:0, val:0},{idx:1, val:1}]};
    JSON.stringify( options);

    Peter

    Comment

    Working...