Answer the question
In order to leave comments, you need to log in
How to convert json file (or content of json file) to javascript string?
There is a list.json file which contains a list of words. I need to translate it into a javascript string. I tried to insert a list by copying from a file into a variable, it did not work out:
var str1 = "[
person
time
business
life
day
hand
times]";
var str2 = json.parse(str1);
Tell me, please, where is the error?
Is it possible to do this in javascript without copying the words into a variable, but by accessing the file. (I'm a complete noob at this, sorry if I'm asking stupid things)
Answer the question
In order to leave comments, you need to log in
You have an error in json string format
var str1 = '["человек", "время", "дело", "жизнь", "день", "рука", "раз"]';
console.log(JSON.parse(str1));
if you are using Node.js then:const list = require('./list.json');
Is it possible to do this in javascript without copying the words into a variable, but by accessing the file
let xhr = new XMLHttpRequest();
xhr.open('GET', 'file.txt', false); // либо "file.json"
xhr.send();
let file = xhr.responseText || '';
// а дальше уже делаете с файлом, что хотите
// либо разбиваете на строки с помощью разделителя "перенос строки"
let strings = file.split(/[\r\n]+/);
// либо разбиваете на слова разделителем "перенос строки или пробел"
let words = file.split(/[\s\r\n]+/);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question