0
var urlArray = window.location.pathname.split("/"),
    idFromUrl = urlArray[2],
    dataPath = "/bulletins/" + idFromUrl + "/data";

$.ajax({
    url: dataPath,
    type: "get",
    dataType: "html",
    success: function (data) {
        var dataObj = data.replace(/"/g, '"');

        console.log(dataObj);
    }
});

I'm grabbing the contents of an HTML page, and the contents on that page is super simple. It's just an "array", although it's plain text so when it returns, JavaScript is treating it as a string instead of an array. This is all that's on that HTML page:

[{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]

Without replace the "'s, a console.log spits out [{"sermontitle":"test","welcome":"test","_id":"52e7f0a15f85b214f1000001"}]

So my question is, how can I turn that HTML string (that's already in "array" form) into an actual array?

5
  • Why the response are with "? Commented Jan 29, 2014 at 1:22
  • How do you mean you get that from an HTML page? How do you have an array? It looks like JSON except the []. JSON has a strong grammar. I would try to strip the [] and then json.parse() it. Commented Jan 29, 2014 at 1:22
  • @dollarvar I'm getting that from an HTML page, cause I'm somewhat hacking a Node view that's built with Jade to just dump all the data on an empty page. Couldn't figure out how to create a JSON file on the fly the way I can with Jade templates. Commented Jan 29, 2014 at 1:31
  • Does stripping the [] and then json.parse() it work? Commented Jan 29, 2014 at 1:33
  • json.parse does indeed work. I'd probably want to strip the [] still though. Do you know how to do that with a regular expression? Commented Jan 29, 2014 at 1:35

3 Answers 3

2

You can use JSON.parse

JSON.parse(dataObj);
Sign up to request clarification or add additional context in comments.

1 Comment

i accidentally clicked delete, too bad :-)
1

You can parse the returned HTML fragment as JSON:

JSON.parse(dataObj);

Comments

1

Change "dataType" to "json" and it will convert it for you:

var urlArray = window.location.pathname.split("/"),
    idFromUrl = urlArray[2],
    dataPath = "/bulletins/" + idFromUrl + "/data";

$.ajax({
    url: dataPath,
    type: "get",
    dataType: "json",
    success: function (data) {
        console.log(data);
    }
});

If it is returning the " instead of ", then I would change the AJAX return page to make sure it is doing a proper JSON response.

2 Comments

Yeah, I tried that but no luck. It just returns nothing. I think it's because it's not actually a JSON file.
Have you used put in JSON headers in the file?

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.