1

I have no idea how to properly 'return' this JSON object (in JavaScript):

function callback() {   
                var points = '{\"points\": [';
                var params = polyline.getLatLngs();

                var i;
                for (i = 0; i < points.length; i++) {
                    params = params.concat('{\"latitude\": ', points[i].lat, ', \"longitude\": ', points[i].lng, '}');
                    if (i < points.length - 1) {
                        params = params.concat(', ');
                    }
                }
                params = params.concat('] }');

                return JSON.parse(params);
            }

I want to catch it with something like (Objective-C):

NSString *s = [self.webView stringByEvaluatingJavaScriptFromString:@"callback();"];

Obviously this results in a NSString, what I really want is NSData to do this (Objective-C):

NSData *data = [s dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:data options:NSJSONWritingPrettyPrinted error:&error];

So, how to properly return the JSON?

2
  • 2
    I'm sorry, did you just construct a JavaScript object in JavaScript by concatenation, then parse it? Commented Mar 20, 2012 at 22:51
  • What @minitech means is that JavaScript natively understands JSON syntax - you don't have to construct a string like that and parse it; you can just create the object directly. Commented Mar 20, 2012 at 22:56

1 Answer 1

1

This should do it:

function callback() {
    var params = polyline.getLatLngs();
    var result = [];
    var i;
    for (i = 0; i < params.length; i++) {
        result.push({latitute: params[i].lat, longitude: params[i].long});
    }

    return JSON.stringify({points: result});
}

Note that JSON.parse generates an object from a string, and JSON.stringify creates a string from an object. No need to do it manually.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.