V
V
VegasChickiChicki2019-04-24 06:36:12
JavaScript
VegasChickiChicki, 2019-04-24 06:36:12

How to access JSON file?

I have a JSON file in the project folder, I need to access it and, for example, display the 'name' field in the console, I can't figure out how to do it. JSON looks something like this:

{
  "projects": [
    {
      "name":"Алеша"
  ]
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anatoly, 2019-04-24
@VegasChickiChicki

Smoke XMLHttpRequest, example:

function readTextFile(file, callback) {
    var rawFile = new XMLHttpRequest();
    rawFile.overrideMimeType("application/json");
    rawFile.open("GET", file, true);
    rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4 && rawFile.status == "200") {
            callback(rawFile.responseText);
        }
    }
    rawFile.send(null);
}

//использование:
readTextFile("/Users/Documents/workspace/test.json", function(text){
    var data = JSON.parse(text);
    console.log(data);
});

I
Ilya Bobkov, 2019-04-24
@heksen

var json = JSON.parse(ваш_json_объект);
console.log( json.projects[0].name )

I
irishmann, 2019-04-24
@irishmann

jQuery.getJSON

$.getJSON("test.json", function(json) {
    console.log(json[0]['name']);
});

test.json - path
Something like this, using JQuery. By the way, the JSON question is not valid.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question