-1

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 in to json .

I have tried below code:

var jsonString = JSON.stringify(myArray);

output as 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 object?

Jaykumar Patel
  • 26,836
  • 12
  • 74
  • 76
Ambili
  • 121
  • 1
  • 1
  • 5

4 Answers4

0

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)
0

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.

David Hughes
  • 381
  • 1
  • 12
0

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"]

0

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

Javascript object Vs JSON

Community
  • 1
  • 1
Dropout
  • 13,653
  • 10
  • 56
  • 109