SirCodesALot said:
Is it possible to create an JSON object from a string?
You really don't mean "JSON object" here. If there would be such a thing,
it would be an object that is referenced by the property with the name
`JSON'. Remember that JSON is a *data exchange format*, not a framework by
itself. The object that results from parsing JSON is a native user-defined
ECMAScript (Object or Array) object.
var myArray = new Array(10)
Passing a number argument in order to initialize the array is unnecessary,
as ECMAScript arrays are of variable length. It is also error-prone, as
implementations differ: in the next-to-worst case you will end up with an
array that has the number value `10' as its first element. Use
var myArray = [];
instead, it can be considered to be safe although not universally supported
(JavaScript 1.3+, JScript 2.0+, ECMAScript 3).
for (var i=0;i<10;i++)
{
myArray.push("{idx:"+i+",val:"+i+"}");
}
Note that Array.prototype.push() requires at least JavaScript 1.2 and, more
important, JScript 5.5. You may want to augment Array.prototype or the
Array object itself with such a method. (If you choose to augment the
Array.prototype object, you should also provide an iterator method that
handles the side-effects of the augmentation.)
<
http://PointedEars.de/es-matrix/>
Also, this only works as long as `i' is not an arbitrary string value.
var myStrObj = "[" + myArray.join(",") + "]";
Array objects inherit a toString() method from Array.prototype that returns
a comma-separated string-converted version of their elements (ECMAScript
Edition 3 Final, section 15.4.4.2). This method is called first on implicit
string conversion (ibid., 8.6.2.6). Therefore,
var myStrObj = "[" + myArray + "]";
suffices.
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?
It is possible. Depending on your JSON-capable framework, you can use
either JSON.parse() (e.g. from json2.js or json_parse.js) or simply eval()
to return the respective object reference; the former is safer but probably
slower than the latter.
Please RTFM next time first: <
http://json.org/>
PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
-- from <
http://www.vortex-webdesign.com/help/hidesource.htm>