1

I am making an API request to the Census API for my Node app. The response I am receiving is an XML string:

"[["POP","DATE","state"],
["735132","6","02"],
["735132","6","02"]]"

I would like to convert it into JSON. I have tried using npm xml2js but I am receiving the following error:
"Non-whitespace before first tag. Line: 0 Column: 1
I dont understand XML, so its makes it difficult to comprehend the error message. Any good ideas how I can convert this response to JSON? Thanks in advance!

4
  • 1
    Why do you think it's an XML stirng if it's a JSON string? Just do a JSON.parse(your_string) Commented Dec 11, 2015 at 17:07
  • 1
    If that's an XML response, I'm losing my mind.... @VsevolodGoloviznin your comment should work Commented Dec 11, 2015 at 17:07
  • 1
    Your example is not an XML string. That's why you can't convert is using xml2js Commented Dec 11, 2015 at 17:08
  • Sorry. I figured an JSON response would be an object {} rather than an array [] Commented Dec 11, 2015 at 17:10

2 Answers 2

2

You are not getting a XML response. It's a parsed JSON string.

So if you want a JSON Object:

var response = "[["POP","DATE","state"], ["735132","6","02"], ["735132","6","02"]]";
var json = JSON.parse(response);
Sign up to request clarification or add additional context in comments.

Comments

1

This is JSON. The problem is it has 2 extra double quotes, at the beginning and the end.

You can do:

var string = stringFromAPI;
var sringWithoutExtraDoubleQuotes = string.substring(1, string.length - 1);
var parsedObject = JSON.parse(sringWithoutExtraDoubleQuotes);

1 Comment

Node might actually parse it without removing the extra double quotes.

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.