简体   繁体   中英

Formatting a JSON Response to build a URL

I'm incredibly stuck on trying to format receive a JSON response, and format it. Order of operations:

  1. Query a REST API endpoint ( https://endpoint.com/api/v1/employee?id={username} )
  2. Receive JSON response: {"employee":{"full name":"Example Name","function":"Role","office":"Office Location",team":"Team 1|Team 2|Team 3|"}}

In my base.js file within my django app, I am hoping to extract the team strings and pass them into another URL. What way can I do this? When I $.getJSON from the endpoint I receive responseJSON, responseText, etc. but I'm unable to pull them out/use them in any way.

In order to fetch and parse json I would suggest you to use the following fetch structure:

fetch('https://endpoint.com/api/v1/employee?id=username')
  .then(response => response.json())
  .then(data => {
    let teams = data.team.split('|');
    // Do something with team names
  });

Let's break down what this does per line:

  1. First we use fetch to request data from the defined url
  2. Then we convert the response to a json object
  3. Finally we retrieve the string with team values using the data.teams statement, after which we immediately convert the list of team names to an array by using split and the defined delimiter | .

After this you should be able to do whatever you'd like with the team names. You could use them to make another API call as well. If you're interested, be sure to checkout the fetch documentation , as well as the split documentation if you are not yet familiar with that function.

The solution above assumes that the response will be a 200, for error handling you should check out the fetch documentation above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM