-3

I have a javascript array

var arr = ["value1", "value2", "value3", "value4", "value5"]

I want to convert it into JSON array to be sent over to server like this

{
  "JSONarray": ["value1", "value2", "value3", "value4", "value5"]
}

Directly putting javascript array varible into the value doesn't help.

Tried JSON.stringify() it converts the whole array into one giant string.

Is there any other approach to this problem?

Gilgamesh
  • 121
  • 2
  • 2
  • 10

2 Answers2

0

To clarify, JSON is a string and not an object hence it's abbreviation of JavaScript Object Notation. The constructed output in the example is colloquially referred to as a POJO or Plain Old JavaScript Object. They are different. :)

JSON exists as a string — useful when you want to transmit data across a network. It needs to be converted to a native JavaScript object when you want to access the data. This is not a big issue — JavaScript provides a global JSON object that has methods available for converting between the two. - MDN

The approach for sending JSON in JavaScript is to use the builtin JSON object's stringify method as you have already discovered.

Jason Cust
  • 10,743
  • 2
  • 33
  • 45
0

You want to use JSON.stringify() to convert the data into a string. This makes it simple when transferring data.

When you or someone receives this string of data, you can convert it to 'json' with JSON.parse()

var JSONarray = JSON.stringify(arr)
// => "["value1","value2","value3","value4","value5"]"
JSON.parse(JSONarray)
// => (5) ["value1", "value2", "value3", "value4", "value5"]
jtrdev
  • 915
  • 1
  • 9
  • 25