0

Before posting, I've read through suggested similar questions, but couldn't find an answer.

I have an array declaration stored in a text.txt file. Let's say the array declaration looks something like this:

["content1-1", ["content2-1", "content2-1"]]

I want to load this as an array into a variable in JavaScript.

This is what I tried:

var data = []

	function loadSOAFile(chineseCharacter) {
		var textfileFileName = "text.txt"
		var rawSOAFile=new XMLHttpRequest();
		rawSOAFile.open("GET",textfileFileName);
		rawSOAFile.onload=function(){
    			console.log(rawSOAFile.responseText);
			data = rawSOAFile.responseText
		}
		rawSOAFile.send();
		
		setTimeout(function() {
                     document.getElementById("debuggingconsole").innerHTML = data[0]
    }, 200);
}

However, when I call the function, instead of writing "content1-1" it writes "[", so clearly it loads the variable as a string rather than an array.

Is there a cleaver way to load it as an array declaration? I don't deal with JS all that often, so answers providing a little bit more context would be most appreciated.

4
  • 1
    what is a "textile" ? Commented Sep 22, 2019 at 20:13
  • Thanks for pointing it out, a "textile" was clearly a misspelled "text file." Luckily, kvsm here came up with a perfect solution to the problem before I even had time to correct it. Kudos Kvsm for not getting distracted by minutiae. Commented Sep 23, 2019 at 21:55
  • 1
    Instead of using setTimeout() to access data[0], perform the assignment to innerHTML within the onload callback so that you're not introducing a race-conditon in your code. Commented Sep 23, 2019 at 21:58
  • @Tyro I am not familiar with English and I have tried in vain to understand if your typographical fault hid a semantic subtlety giving a particular meaning to your question. It was not a "distraction" for me, and I feel you're mocking me. Commented Sep 23, 2019 at 22:20

1 Answer 1

1

If the array is formatted as you describe, then it's valid JSON. You can retrieve the values from the string by parsing it as such:

data = JSON.parse(rawSOAFile.responseText)
Sign up to request clarification or add additional context in comments.

3 Comments

This is brilliant. Thank you so much, works like a charm.
@Tyro if the answer solved your problem, please click to accept the answer.
I’ve just “ticked it off.” I hope that’s what you meant by “accept the answer.”

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.