Translating from JavaScript to Objective-C using JSON

Can someone help me figure out how to correctly 'return' this JSON object in JavaScript?

function getJSONData() {   
                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 am looking to grab this data using something like the following Objective-C code:

NSString *jsonDataString = [self.webView stringByEvaluatingJavaScriptFromString:@"getJSONData();"];

However, I need the data to be in NSData format instead of NSString. How can I achieve this conversion properly in Objective-C?

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

Any suggestions on how to achieve this conversion from JSON as desired?

Answer №1

Here is the solution:

function processData() {
    var data = shape.getCoordinates();
    var formattedData = [];
    var index;
    for (index = 0; index < data.length; index++) {
        formattedData.push({latitude: data[index].lat, longitude: data[index].long});
    }

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

Remember that JSON.parse converts a string to an object, while JSON.stringify changes an object into a string. You don't have to handle this manually.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to proceed due to lint errors; after conducting research, the issue still remains

I'm still getting the hang of tslint and typescript. The error I'm encountering has me stumped. Can someone guide me on resolving it? I've searched extensively but haven't been able to find a solution. Sharing my code snippet below. (n ...

Transferring Parameters to EJS Template in Node.js

Hey guys, I'm having an issue with rendering a MongoDB record in my .ejs file. Strangely, when I console.log the variable before the end of my route, I get the expected value. However, it becomes undefined in the .ejs file. Here is the code snippet: ...

The identical page content is displayed on each and every URL

Implementing a multi-step form in Next JS involves adding specific code within the app.js file. Here is an example of how it can be done: import React from "react"; import ReactDOM from "react-dom"; // Other necessary imports... // Add ...

Creating interactive dropboxes in PHP and JavaScript to dynamically change options and display the selected value

Currently, I am in the process of working on a dynamic dropdown menu that involves select boxes. These values are being pulled directly from a MySQL database (if you're interested, here is how I set up the database). I have successfully retrieved and ...

Retrieve user information from Auth0 once the user has completed the signup process

I am looking to integrate the ability to create new users on Auth0 through my admin panel. Currently, I am utilizing Auth0 lock for signups, but now I need to store these users in my Database, which requires their email and Auth0 user ID. I am exploring o ...

Getting the parent object based on a filtered nested property can be achieved by utilizing a

I am currently facing an issue with filtering an array of nested objects. The problem arises when trying to filter the parent object based on a specific property within its child object. let line = "xyz"; let data = [ { "header": { ...

"Converting a standard grammar with recursion and alternations into a regular expression: A step-by-step

A grammar is considered regular if it follows either a right-linear or left-linear pattern. According to this tutorial, this type of grammar possesses a unique property: Regular grammars have a special characteristic: through the substitution of every no ...

What is the best way to retrieve the present value of an input that belongs to an array of objects?

Struggling with populating an array with data and encountering a specific issue. 1 - Attempting to determine an index for each key in the array of objects, but encountering an error when a new input is added dynamically. The inputs are successfully added ...

I want to locate every child that appears after the <body> element, and extract the HTML of the element containing a specific class within it

It may sound a bit confusing at first, but essentially I have some dynamically generated HTML that resembles the following: <body> <div class="component" id="465a496s5498"> <div class="a-container"> <div class="random-div"> ...

If I do not utilize v-model within computed, then computed will not provide a value

I'm fairly new to coding in JS and Vue.js. I've been attempting to create a dynamic search input feature that filters an array of objects fetched from my API based on user input. The strange issue I'm coming across is that the computed metho ...

How to Retrieve the Name of the Active Element from an Unordered List (<ul>) in ReactJS and Display it in the

I have a project where I am creating a long navbar specifically for mobile devices, and I am structuring it in an accordion style. Initially, the view will show the currently active link name. When the user clicks on this active link name, it expands below ...

What is the process of extracting information from a JSON file and how do I convert the Date object for data retrieval?

export interface post { id: number; title: string; published: boolean; flagged: string; updatedAt: Date; } ...

The scatterplot dots in d3 do not appear to be displaying

My experience with d3 is limited, and I mostly work with Javascript and jQuery sporadically. I am attempting to build a basic scatterplot with a slider in d3 using jQuery. The goal of the slider is to choose the dataset for plotting. I have a JSON object ...

Using Vue.js to update content in input files

I have a Vue.js template file that includes data containing various documents. Within the page, there is a table with rows that feature upload file input buttons, structured like this: <tr v-for="(doc, index) in documents"> <td :id="'doc-& ...

Leveraging a function for filtering in AngularJS

I have developed an application where the content filter changes depending on which button is clicked. I have managed to figure out the straightforward filters, but now I am attempting to create a filter that displays content within a specified range. Bel ...

Tips for pinpointing parent elements within a group of various sub child elements

CSS - <div class="windows" id="window'+divCount+'"> <p id="windowName'+divCount+'"></p> <p id="para'+divCount+'">Source</p> </div> <div cla ...

Can we make this happen? Navigate through slides to important sections, similar to vertical paging

Imagine a website with vertical "slides" that take up a significant portion of the screen. Is there a way to smoothly add vertical paging to the scrolling? For example, when the user scrolls close to a specific point on the page horizontally, the page will ...

The tally of seconds within a year has been altered

I have developed a function that converts inputted seconds into an output format of Years, Days, Hours, Minutes, and Seconds for the user. While I am still refining the various outputs and improving the syntax, I am currently focused on identifying a calcu ...

Verify whether the JSON response includes an object

I am attempting to determine if a JSON response contains objects, and execute a specific action if it does. The issue I'm facing is that even when the response includes objects, the break statement does not trigger. Below is the code snippet I am wo ...

Using JavaScript to Redirect to Homepage upon successful Ajax response on local server

I need assistance with redirecting to the Homepage from the SignIn Page once the user credentials have been validated. The response is working correctly, and upon receiving a successful response, I want to navigate to the Homepage. My setup involves Javasc ...