Reputation: 151
In an Apigee JS script, I have an array like this:
["test","test group 2","test group 4","test group 4","test group 5","test group 6"]
I need to convert this array into JSON.
I have tried the code below:
var jsonString = JSON.stringify(myArray);
but I get output like this:
org.mozilla.javascript.NativeArray@617586ce
I have tried json parsing also but did not work. How can I convert it to a JSON string?
Upvotes: 0
Views: 1982
Reputation: 13866
If you want to create a JSON object by parsing, then you need a valid JSON string. For example
var jsonString = "[\"test\",\"test group 2\",\"test group 4\",\"test group 4\",\"test group 5\",\"test group 6\"]";
var jsonObject = JSON.parse(jsonString);
console.log(jsonObject);
The JSON.stringify()
method is used for conversion from an object to a string.
Check out the following links, where it's explained how to use JSON in JavaScript.
http://www.w3schools.com/js/js_json.asp
http://www.w3schools.com/json/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Upvotes: 0
Reputation: 680
This should be work, try:
var a = JSON.parse("[\"test\",\"test group 2\",\"test group 4\",\"test group 4\",\"test group 5\",\"test group 6\"]")
console.log(a)
Result:
["test", "test group 2", "test group 4", "test group 4", "test group 5", "test group 6"]
Upvotes: 0
Reputation: 370
You can use JSON.parse(x)
to attempt to convert from a string to a javascript object.
Do NOT use eval unless you have a very specific reason.
Upvotes: 0
Reputation: 87
you can try below code.
var o = '["test","test group 2","test group 4","test group 4","test group 5","test group 6"]';
var arr = JSON.stringify(o);
alert(arr)
Upvotes: 0