1

I want to get the data directly from the JSON file to javascript variable (data) how can I do it I use asp.net core and the JSON file in the root.

var data = Jsonfile;

json file have this

[
    {
      "description" : "twitter",
      "link" : "https://twitter.com/digitalocean"
    },
    {
      "description" : "facebook",
      "link" : "https://www.facebook.com/DigitalOceanCloudHosting"
    },
]

2 Answers 2

1

You could get JSON file data in an action and call this action using fetch/ajax in javascript.

Refer to my demo where myData.json is located in the root of project and use HomeController as an example.

1.HomeController.cs

public class HomeController : Controller
{
    private readonly IHostingEnvironment _hostingEnvironment;

    public HomeController(IHostingEnvironment hostingEnvironment)
    {
        _hostingEnvironment = hostingEnvironment;
    }

    public IActionResult GetJsonValue()
    {
        string contentRootPath = _hostingEnvironment.ContentRootPath;
        string path = Path.Combine(contentRootPath, "myData.json");
        var JSON = System.IO.File.ReadAllText(path);
        var jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(JSON);
        return new JsonResult(jsonObj);
    }
}

2.Javascript

 //use ajax
 $.ajax({
        type:"GET",
        url: "/Home/GetJsonValue"

    }).done(
        function(data){
            console.log(data);
        });
 //or use fetch
 fetch("/Home/GetJsonValue")
        .then((response) => {
            return response.json();
        })
        .then((myJson) => {
            console.log(myJson);
        });
Sign up to request clarification or add additional context in comments.

Comments

0

You'll need to fetch the file from the directory. The fetch function will return a promise. When a response is returned it has to be read as JSON. After that your JSON data is available to use in the next callback.

fetch('./relativepath/jsonfile.json')
  .then(response => response.json()) 
  .then(data => {
    // Use your json here. It is stored in the data variable.
  });

You could create an async function to make the code reusable.

async function getJson(resource)
  const response = await fetch(resource);
  const data = await response.json();
  return data;
}
getJson('./relativepath/jsonfile.json').then(data => {
  // Use your json here.
});

2 Comments

when i make the frist one it give me this error in the browser console he think the json file in the home but it's in the root directly Failed to load resource: the server responded with a status of 404 ()
Okay, well. Then the next step will be to figure out how to get the correct path to the file and expose it to JavaScript. Good luck!

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.