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();