Click here to Skip to main content
15,867,594 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a simple json file that have
[{"Min":1,"Max":5770}]

I want get Min and Max data from Json
How can i get? Thanks

What I have tried:

var Min = null;
var Max = null;

        $.getJSON('Content/ApexData/MinMax.json', function (response) {
            Min = response.Min;
            Max = response.Max; 
        });
Posted
Updated 10-Mar-21 4:25am

1 solution

Your JSON file is an array containing a single object. Therefore, you need to take the properties from the first item in that array.
JavaScript
$.getJSON('Content/ApexData/MinMax.json').then(function(response){
    var value = response[0];
    Min = value.Min;
    Max = value.Max;
});
Also bear in mind that the "A" in "AJAX" stands for "asynchronous". Your variables will not be assigned until the request to the server has been completed and the callback has executed. If you attempt to access them immediately after the $.getJSON call, they will not have been initialized yet.
JavaScript
$.getJSON(...).then(...);
console.log("Min", Min, "Max", Max); // <-- Variables will still be null here...
You will potentially need to rewrite your code so that you don't try to access the variables before the AJAX request completes.

You may find it easier to use an async function:
async function - JavaScript | MDN[^]
JavaScript
(async function(){
    let response = fetch('Content/ApexData/MinMax.json');
    if (!response.ok) {
        let errorMessage = await response.text();
        console.error(response.status, response.statusText, errorMessage);
        alert("There was an error loading the min/max data.");
        return;
    }
    
    let result = await response.json();
    let value = result[0];
    let Min = value.Min;
    let Max = value.Max;
    
    ... Use min and max here...
})();
 
Share this answer
 
Comments
gacar 10-Mar-21 10:32am    
Worked. Many thanks for solution and explains

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900