A
A
Anna2018-08-22 15:33:35
JavaScript
Anna, 2018-08-22 15:33:35

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

3 answer(s)
M
Medin K, 2018-08-22
@medin84

You have an error in json string format

var str1 = '["человек", "время", "дело", "жизнь", "день", "рука", "раз"]';
console.log(JSON.parse(str1));

S
Stockholm Syndrome, 2018-08-22
@StockholmSyndrome

if you are using Node.js then:
const list = require('./list.json');

N
Nick Sdk, 2018-08-23
@lidacriss

Is it possible to do this in javascript without copying the words into a variable, but by accessing the file

Well actually yes
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 question

Ask a Question

731 491 924 answers to any question