1

This answer looked pretty close but I think there's a fundamental difference between this answer and my problem that makes the answer insufficient for my needs.

From an ajax post, I'm getting a JSON value returned that looks like this:

{
   "token": "wegHOIoi32h4gt834ygli",
   "expires": "1496845449"
}

I need to save the token value wegHOIoi32h4gt834ygli into localStorage.

Here's my code:

$.ajax(settings).done(function (response) {
    console.log(response);
    $(".Results").html(response);
    $.each(response, function (index, element) {
        var token = element.value;
        console.log(token);
        localStorage.setItem("token", token);
    })
});

Now I'm getting this error:

Uncaught TypeError: Cannot use 'in' operator to search for '326' in {
"token": "wegHOIoi32h4gt834ygli",
"expires": 1496845449
}

Pretty sure I don't have any idea what's going on at this point. How can I extract the value I'm looking for?

Ortund
  • 8,095
  • 18
  • 71
  • 139

1 Answers1

2

Assuming the API response is a string, you'll need to parse it into an object with JSON.parse(responseString). This then gives you a plain JavaScript object that you can manipulate and extract values from.

For example, assuming the response is the one from your question:

$.ajax(settings).done(function (response) {
    var parsedResponse = JSON.parse(response);
    var token = parsedResponse.token;
    console.log(token); // "wegHOIoi32h4gt834ygli"
});

Alternatively, if your API is correctly sending it's response with Content-Type: application/json, or you tell jQuery to parse it as JSON for you (see dataType: "json" in the documentation), then the problem is coming from the fact that $.each tries to iterate over an array of value, which you don't have, so you can simply do this:

$.ajax(settingsIncudingDataType).done(function (response) {
    var token = response.token;
    console.log(token); // "wegHOIoi32h4gt834ygli"
});
Mark Ormesher
  • 2,289
  • 3
  • 27
  • 35
  • The JSON parsing did it :) I actually had the link for JSON.Parse open on w3schools but figured I could save myself some time by asking before I implemented it. – Ortund Jan 09 '19 at 09:05
  • Glad it worked for you! One thing I find really helpful for quickly experimenting with JS is having Node.js installed on my machine, so I can quickly drop into an interactive Node console - might be worth setting that up if you work on JS often. Also, if this solved it for you, could you mark it as accepted? – Mark Ormesher Jan 09 '19 at 09:23
  • I was trying to mark as accepted but it wouldn't let me lol also I have Node.js since I'm starting Angular but I don't know how to do this thing that you're suggesting with it – Ortund Jan 09 '19 at 09:25
  • If you have Node.js installed on your machine, you should just be able to type `node` in your terminal to start an interactive session. From there you can type JS code and see the results immediately. – Mark Ormesher Jan 09 '19 at 09:30