1

This might be a stupid question, but I'm a noob who's been looking into this all day yesterday and today and having trouble finding a clear answer.

I am having issues isolating the value from a single key:value pair in a JSON API call. In my code below, I am trying to make a call to a locally hosted JSON file and want to GET the value of "maxFileSize".

The JSON being called would look something like the following {"maxFileSize" : "10MB"}. I want to GET the value using the object key "maxFileSize" and append it to my div tag in my HTML. What am I doing wrong?

<div id="randominfo"></div>

<script src="jquery-3.2.1.min.js"></script>
<script>

  $(document).ready(function(){
   $.getJSON('http://localhost/MISREST/images', function (data) {
      $.each( JSON.parse(data), function ( key, val ) {
        $("#randominfo").append(data.maxFileSize + " "); 
    });
});



});


</script>

UPDATE

Here is the C# code generating the JSON data. The JSON is renamed to MISREST/images in another C# file:

    public string JSONGetImageFiles()
    {
        if (Directory.Exists(SmSystemConfig.ImageFilePath))
        {
            DirectoryInfo dir = new DirectoryInfo(SmSystemConfig.ImageFilePath);
            FileInfo[] fileEntries = dir.GetFiles();
            StringBuilder toReturn = new StringBuilder("");

            toReturn.Append("{\"maxFileSize\" : \"10 MB\", \"fileList\" : [");

            if (fileEntries.Length != 0)
            {
                int count = 0;
                foreach (FileInfo file in fileEntries)
                {
                    if (file.Extension.ToLower() == ".jpg" || file.Extension.ToLower() == ".png" || file.Extension.ToLower() == ".gif")
                    {
                        count++;
                        toReturn.AppendFormat("{{\"fileName\" : \"{0}\", \"href\" : \"{1}{2}\",", file.Name.Remove(file.Name.LastIndexOf(".")), SmSystemConfig.ImagePath, file.Name);
                        toReturn.AppendFormat("\"uploadDate\" : \"{0}\",", file.CreationTime.ToString("MM/dd/yyyy"));
                        toReturn.AppendFormat("\"fileSize\" : \"{0}\"}},", GetFileSize(file.Length));
                    }
                }
                if (count != 0)
                    toReturn.Replace(",", "]}", toReturn.Length - 1, 1);
                else
                    toReturn.Append("\"None\"]}");
            }
            else
            {
                toReturn.Append("\"None\"]}");
            }
            return toReturn.ToString();
        }
        else
        {
            WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.NotFound;
            WebOperationContext.Current.OutgoingResponse.StatusDescription = "Directory Not Found";
            return "{ \"errorMessage\" : \"generror\" }";
        }
    }

C# File where API paths are defined (this is the section where the images filepath is defined):

    [WebInvoke(
        Method = "GET",
        BodyStyle = WebMessageBodyStyle.Bare,
        UriTemplate = "images",
        ResponseFormat = WebMessageFormat.Json)]
    [OperationContract]
    string JSONGetImageFiles();
2
  • The response of $.getJSON is a plain object. Won't $.each(data,... work? Commented May 15, 2017 at 14:37
  • It's multiple objects in one call. Commented May 15, 2017 at 14:41

2 Answers 2

2

It's not totally clear to me which of these is the case, but based on your C# code and your comment on the answer above, your JSON file is either a single object (meaning .each is not needed to access data within it) or it's a series of objects without any delimiters between them (meaning JSON.parse should be throwing an error.)

Assuming a single object, you would get the maxFileSize like so:

var data = '{"maxFileSize" : "10 MB", "fileList" : [{"fileName" : "1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat", "href" : "../Images/1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat.jpg"}]}';

$('#go').click(function() {
  $("#randominfo").append(JSON.parse(data).maxFileSize + " ");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="go">Go</button>
<div id="randominfo"></div>

Assuming what you're really trying for is an array of objects, the JSON needs to be structured as an array, and when iterating through that array you need to be referring to each object inside the array instead of to the parent data like you're doing:

var data = '[{"maxFileSize" : "10 MB", "fileList" : [{"fileName" : "1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat", "href" : "../Images/1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat.jpg"}]}, {"maxFileSize": "20MB", "fileList": []}]';


$('#go').click(function() {
  $.each(JSON.parse(data), function(key, val) {
    $("#randominfo").append(val.maxFileSize + " "); // <-- not data.maxFileSize
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button id="go">Go</button>
<div id="randominfo"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

Try referring to the val that's being passed as function argument within the each function:

$.each( JSON.parse(data), function ( key, val ) {
   $("#randominfo").append(val.maxFileSize + " "); 
});

5 Comments

And what does a console.log(data) before the each function prints?
{"maxFileSize" : "10 MB", "fileList" : [{"fileName" : "1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat", "href" : "../Images/1_Exterior Cabinet_Cabinet C_Economizer_Econ_Exhaust_Gas Heat.jpg", and the JSON continues
Yep, your fiddle seems to work but the same code isn't working on my end. I added the C# code that populates the JSON data above for reference
I'm not able to talk about C#, but I think the main issue is in the way you're trying to access to data check if it's well formatted.
I managed to get it to work just using console.log(val) instead of console.log(val.maxFileSize). Thanks for the help

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.