admin管理员组

文章数量:1302266

I am trying to use JavaScript and jQuery to read a local JSON file and create a dictionary of key/value pairs that I can later iterate to set the selected value of several drop down lists.

I have a map.json file as follows;

[
  { 
    "map_recipient_name": "Tax payer Name",
    "map_delivery_pany_name": null,
    "map_delivery_street_address": "Address1",
    "map_delivery_apt_suite": "Address2",
    "map_delivery_city": "City",
    "map_delivery_state": "State",
    "map_delivery_zip": "Zip",
    "map_delivery_zip_4": "Zip+4",
    "map_customer_reference_number": "Notice Number",
    "map_notice": null,
    "map_recipient_email": null,
    "map_send_email": null,
    "map_standardize_address": null
  }
]

Each key is the ID of one of my Select HTML controls and the value is the desired Selected value for the specified control.

I am using an HTML input type=file control to allow the user to select the map.json file shown above on the local file system and I am using a FileReader ReadAsText method to read the contents into a local variable. Then I want to parse the string into a dictionary of key/value pairs that I will later iterate to set the "Selected" value of a series of Select HTML controls.

I am using the code below but it doesn't seem to be able to successfully get the JSON string key/value pairs into the dictionary.

var field_mapping = document.getElementById('fieldmapping')
function read_map_file(e) {
    var map_file = e.target.files[0]
    if (!map_file) {
        return;
    }
    var dict = {};
    var reader = new FileReader();
    reader.onload = function (e) {
        var json = e.target.result;
        var result = JSON.parse(json);
        $.each(result, function (key, value) {
            alert(key + ' is ' + value);
            //dict[key] = value;
        });
    };
    reader.readAsText(map_file);

}

if (field_mapping.addEventListener) field_mapping.addEventListener('change', read_map_file, false);

When I run this code and select the map.json file, I can see the string of text in the debugger when I examine the value of the json variable immediately after the line...

var json = e.target.result;

... executes. I can see that it has enclosed the JSON text with beginning and trailing double quotes (which I assume are because of the ReadAsText method of the reader).

When I examine the next line...

var result = JSON.parse(json);

... and I expand the "0: object" line in the debugger, I can see that the string has been parsed and the key/value pairs appear to be correct. However, when the alert pops up in the next section of code...

$.each(result, function (key, value) {
    alert(key + ' is ' + value);
    //dict[key] = value;
});

... The alert dialog says "0 is [object Object]"

ultimately what I want to do is save these key/value pairs into the dict variable so that I can then query the dictionary and get the selected value for each of the select controls.

This is probably something simple, but I am just not seeing it.

Any help would be greatly appreciated.

As a bonus, if anyone has a simpler way to read a local JSON file and use the values to set the Selected values of Select HTML controls, I would love to see it.

Thanks in advance for any help you can offer.

I am trying to use JavaScript and jQuery to read a local JSON file and create a dictionary of key/value pairs that I can later iterate to set the selected value of several drop down lists.

I have a map.json file as follows;

[
  { 
    "map_recipient_name": "Tax payer Name",
    "map_delivery_pany_name": null,
    "map_delivery_street_address": "Address1",
    "map_delivery_apt_suite": "Address2",
    "map_delivery_city": "City",
    "map_delivery_state": "State",
    "map_delivery_zip": "Zip",
    "map_delivery_zip_4": "Zip+4",
    "map_customer_reference_number": "Notice Number",
    "map_notice": null,
    "map_recipient_email": null,
    "map_send_email": null,
    "map_standardize_address": null
  }
]

Each key is the ID of one of my Select HTML controls and the value is the desired Selected value for the specified control.

I am using an HTML input type=file control to allow the user to select the map.json file shown above on the local file system and I am using a FileReader ReadAsText method to read the contents into a local variable. Then I want to parse the string into a dictionary of key/value pairs that I will later iterate to set the "Selected" value of a series of Select HTML controls.

I am using the code below but it doesn't seem to be able to successfully get the JSON string key/value pairs into the dictionary.

var field_mapping = document.getElementById('fieldmapping')
function read_map_file(e) {
    var map_file = e.target.files[0]
    if (!map_file) {
        return;
    }
    var dict = {};
    var reader = new FileReader();
    reader.onload = function (e) {
        var json = e.target.result;
        var result = JSON.parse(json);
        $.each(result, function (key, value) {
            alert(key + ' is ' + value);
            //dict[key] = value;
        });
    };
    reader.readAsText(map_file);

}

if (field_mapping.addEventListener) field_mapping.addEventListener('change', read_map_file, false);

When I run this code and select the map.json file, I can see the string of text in the debugger when I examine the value of the json variable immediately after the line...

var json = e.target.result;

... executes. I can see that it has enclosed the JSON text with beginning and trailing double quotes (which I assume are because of the ReadAsText method of the reader).

When I examine the next line...

var result = JSON.parse(json);

... and I expand the "0: object" line in the debugger, I can see that the string has been parsed and the key/value pairs appear to be correct. However, when the alert pops up in the next section of code...

$.each(result, function (key, value) {
    alert(key + ' is ' + value);
    //dict[key] = value;
});

... The alert dialog says "0 is [object Object]"

ultimately what I want to do is save these key/value pairs into the dict variable so that I can then query the dictionary and get the selected value for each of the select controls.

This is probably something simple, but I am just not seeing it.

Any help would be greatly appreciated.

As a bonus, if anyone has a simpler way to read a local JSON file and use the values to set the Selected values of Select HTML controls, I would love to see it.

Thanks in advance for any help you can offer.

Share asked May 8, 2017 at 20:27 EiEiGuyEiEiGuy 1,5475 gold badges19 silver badges35 bronze badges 1
  • I am curious why the down vote? The down vote tool tip says "The question does not show any research effort; it is unclear or not useful." However, I put a lot of research into this and I feel what I was asking was clear. – EiEiGuy Commented May 9, 2017 at 12:28
Add a ment  | 

3 Answers 3

Reset to default 4

Your JSON.parse() statement is returning an Array. Then when you write:

$.each(result, function (key, value) {
    alert(key + ' is ' + value);
    //dict[key] = value;
});

you are iterating that array and attempting to treat the one and only item in the array (an Object) like it has a key and a value, when it only has a value. You need to get the key and value out of the object stored in result[0], so you need to dig another layer down.

Since there is only one item in the array $.each() is overkill. Where you want to loop is with the object stored in position 0 of the array, not the array itself.

This is what you need:

for(var key in result[0]){
  alert(key + ' is ' + result[0][key]);
}

Here's the working code:

var jsonString = JSON.stringify([
  { 
    "map_recipient_name": "Tax payer Name",
    "map_delivery_pany_name": null,
    "map_delivery_street_address": "Address1",
    "map_delivery_apt_suite": "Address2",
    "map_delivery_city": "City",
    "map_delivery_state": "State",
    "map_delivery_zip": "Zip",
    "map_delivery_zip_4": "Zip+4",
    "map_customer_reference_number": "Notice Number",
    "map_notice": null,
    "map_recipient_email": null,
    "map_send_email": null,
    "map_standardize_address": null
  }
]);

var result = JSON.parse(jsonString);

for(var key in result[0]){
 console.log(key + ' is ' + result[0][key]);
}

You wrapped your JSON file in an array, so you want to loop over result[0] and not result.

$.each(result[0], function (key, value) {
    ...
});

Or you can just remove the surrounding [] in your JSON file if you have control over that, and your code should work as is.

You've pretty much got the data in a 'dictionary', or as Javascript calls it, an object. All you need to do is first iterate over the outer array, then the keys of the inner objects. Try this:

// imagine this is the content returned from your file reader in e.target.result

var result = [{
  "map_recipient_name": "Tax payer Name",
  "map_delivery_pany_name": null,
  "map_delivery_street_address": "Address1",
  "map_delivery_apt_suite": "Address2",
  "map_delivery_city": "City",
  "map_delivery_state": "State",
  "map_delivery_zip": "Zip",
  "map_delivery_zip_4": "Zip+4",
  "map_customer_reference_number": "Notice Number",
  "map_notice": null,
  "map_recipient_email": null,
  "map_send_email": null,
  "map_standardize_address": null
},{
  "map_recipient_name": "Tax payer Name #2",
  "more data goes here...": "foobar"
}];

result.forEach(function(o) {
  Object.keys(o).forEach(function(key) {
    console.log(key + ' = ' + o[key]);
  })
});

本文标签: javascriptHow do I read a JSON file and load the keyvalue pairs in to a dictionaryStack Overflow