Obtain JSON data using a JSONP fetch promise method

As I embark on my journey with react-native, I have chosen the classic example found in the documentation as my starting point...

fetch('https://facebook.github.io/react-native/movies.json')
  .then((response) => response.json())
  .then((responseJson) => {
    return responseJson.movies;
  })
  .catch((error) => {
    console.error(error);
  });

Everything seems to be working well when dealing with proper JSON data in this example.

However, in the scenario specific to my project, the API only provides JSONP responses and not plain JSON. There is no basic JSON available, so an error related to the "(" character arises.

Instead of receiving structured JSON like

{"id": "1", "movies" : [ { "id" : "123" } ] }

I am presented with JSONP format like

?( {"id": "1", "movies" : [ { "id" : "123" } ] });

Given this situation, I'm uncertain about how to extract the JSON content using fetch promises. Is there a way for me to manipulate the response using my own functions, or perhaps a more seamless approach?

In the first then() block, I am puzzled about how to access the actual JSON data (I've attempted working with the response, but it appears to refer to the promise itself, leaving me unsure about how react-native fetch handles such scenarios).

Answer №1

For optimal results, my recommendation would be to utilize response.text() in place of response.json(), eliminate any unnecessary data, and proceed with parsing the JSON string accordingly.

fetch('YOUR URL HERE')
  .then((response) => response.text())
  .then((responseText) => {
    const match = responseText.match(/\?\((.*)\);/);
    if (!match) throw new Error('invalid JSONP response');
    return JSON.parse(match[1]).movies;
  })
  .catch((error) => {
    console.error(error);
  });

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

Guidelines for integrating Pinia seamlessly into Vue 3 components

How should Pinia's store be correctly used in Vue 3 components? Option A const fooStore = useFooStore(); function bar() { return fooStore.bar } const compProp = computed(() => fooStore.someProp) Option B function bar() { return useFooStore( ...

Having a hard time implementing a subtracting callback function in a JavaScript reduce function

Currently, I am tackling a code challenge in JavaScript that requires me to develop a function called reduce. This function is responsible for reducing a collection to a value by applying a specific operation on each item in the collection over which it it ...

Is there a way to assign the value of a textfield to a session attribute in JSP prior to rendering?

Imagine I have the following code snippet: <html> <head> <script> function setSession() { var roll=document.getElementById("rollno").value; session.setAttribute("rollno", roll); } & ...

React - optimize performance by preventing unnecessary re-renders of an object property

In my current project, I am working with an auction object that has two properties: remainingTime and amount. To enhance user experience, I integrated a countdown timer using the react-countdown-now library to display the remainingTime. Additionally, there ...

Associate the ng-model with ng-options value and label

I'm currently using ng-options to create a select tag that displays location options. The labels represent the location names, while the values indicate the corresponding location ID as stored in the database. In addition to binding the value (locati ...

Automatically Activate/Deactivate a button

I am working on a project with a button for asking questions and a countdown timer set to end at 2017/04/30 10:30:00. My goal is to have the button automatically disable when the timer reaches 0, and then re-enable when the timer is greater than 0. Curren ...

Using Knockout along with Ajax content leads to various binding issues

After creating a complex web application with numerous pages, I encountered an issue while implementing Ajax-optimized page loading for Knockout-driven pages. The structure of my pages includes: <body> <div id="content"> </div> < ...

Exploring the Power of Integrating SignalR 2 with a Database

After going through a tutorial on creating a basic messaging web application using SignalR and MVC, I realized that the tutorial did not cover how to store messages in a database or display previous messages to users. The main code snippet from the tutoria ...

Display/Conceal/Inactivate form input and division

I am utilizing the code snippet below to display a div and disable certain input values based on selection changes. The choices are Approval, Request, and Change. I suspect there is an issue with the third set of form options in my code. How can I modify i ...

Showing nested SVGs with custom formatting

I have a nested SVG (path) that I want to manipulate by centering and scaling the "inner" SVG relative to an "inner bounding box" - let's say a square of 500px^2. However, I am struggling with understanding how to adjust the viewport and scaling to ac ...

Waiting for XHR to complete before dealing with asynchronous problem in OBJLoader

In need of assistance on how to make OBJLoader solely return the object without adding it to the scene. I am encountering a synchronization issue where my code does not properly wait for the XHR request, resulting in errors. Check out the example below: ...

Guide on decoding JSON file generated from curl in PHP

After executing my cURL request, the following code is executed: $response = curl_exec($curl); $err = curl_error($curl); curl_close($curl); if ($err) { echo "cURL Error #:" . $err; } else { echo $response; } The respons ...

Tips for generating a random number and verifying if it matches the user input using inner HTML

I'm striving to create something more advanced than what I currently have, but I've hit a roadblock. My goal is to use the method Math.floor(Math.random()*11) to produce a random number. Then, I want to populate the inner HTML of a <p>, alo ...

Learn how to extract the first occurrence of repeated data fields by parsing JSON using the org.JSON library in Java

I need help extracting the initial occurrence of "actualEPS" from this JSON file: {"symbol":"AAPL","earnings":[{"actualEPS":2.34,"consensusEPS":2.17,"estimatedEPS":2.17,"announceTime":"AMC","numberOfEstimates":10,"EPSSurpriseDollar":0.17,"EPSReportDate ...

Setting the value of 'this' in a JavaScript constructor

As I delve into learning JavaScript and experiment with the html5 canvas API, a common hurdle I encounter is the need to create a canvas element and obtain both 2D and 3D context separately. It got me thinking about merging these two entities into one cohe ...

Journey Swiftly Control

I have a question. Is it possible to manipulate routes in Express? Can I assign multiple routes to the same get or post request when providing an address? module.exports = function (app) { var controller = app.controllers.maps.cliente; app.route(&apos ...

Spicing up javascript with Currie's arrow function

Can you please break down this function in a straightforward way (without using arrows)? I'm having trouble understanding if "foo" in Promise.resolve "foo" is an argument or a callback function. module.exports = function foo(req, res, next) { retu ...

Utilizing ReactJS to display a new screen post-login using a form, extracting information from Express JSON

I am facing a challenge with updating the page on my SPA application after a successful login. I have successfully sent the form data to the API using a proxy, but now the API responds with a user_ID in JSON format. However, I'm struggling with making ...

When the script is placed at the end of the file, document.getElementById() is still returning null

I need assistance with running a JavaScript function that is located at the end of my .aspx file. This is the div tag in question: <div id="div_NRContainer" oninit="div_NRContainer_Init" class="panelContainer" runat="server"> Following this, with ...

WebAPI Problem: the challenge of transmitting customer object from client to action

While attempting to execute CRUD operations using a web API, I pass customer JSON data from the client to the API action. Below is the JSON structure that was passed from the client to the action: {"CustomerID":"James","CompanyName":"jame pvt","ContactNa ...