Asked  7 Months ago    Answers:  3   Viewed   34 times

I have an Array var cars = [2,3,..] which holds a few integers. I've added a few values to the array, but I now need to send this array to a page via jQuery's .get method. How can I convert it to a JSON object for sending?



Script for backward-compatibility:

And call:

var myJsonString = JSON.stringify(yourArray);

Note: The JSON object is now part of most modern web browsers (IE 8 & above). See caniuse for full listing. Credit goes to: @Spudley for his comment below

Tuesday, June 1, 2021
answered 7 Months ago

As it stands you're converting it to data, then attempting to convert the data to to an object as JSON (which fails, it's not JSON) and converting that to a string, basically you have a bunch of meaningless transformations.

As long as the array contains only JSON encodable values (string, number, dictionary, array, nil) you can just use NSJSONSerialization to do it.

Instead just do the array->data->string parts:

Swift 3/4

let array = [ "one", "two" ]

func json(from object:Any) -> String? {
    guard let data = try? object, options: []) else {
        return nil
    return String(data: data, encoding: String.Encoding.utf8)

print("(json(from:array as Any))")

Original Answer

let array = [ "one", "two" ]
let data = NSJSONSerialization.dataWithJSONObject(array, options: nil, error: nil)
let string = NSString(data: data!, encoding: NSUTF8StringEncoding)

although you should probably not use forced unwrapping, it gives you the right starting point.

Wednesday, June 2, 2021
answered 7 Months ago

In modern browsers you can simply use JSON.stringify(someJSObject) to convert any JavaScript object (that includes arrays) to a JSON string.

To ensure it also works in less modern browsers, include on your page.

Friday, September 24, 2021
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :