小能豆

How to get json data from texarea or file in js?

java

There is a .txt file that contains json:

{
  "com": "ip",
  "res": [
    {
      "add": "04554E9",
      "m": "6773CYU",
      "default": false,
    },
    {
      "add": "4CECEC58F23",
      "m": "32DW4N",
      "default": true,
    },
    {
      "add": "6E3458",
      "m": "9ANYJ6C5ZVAM",
      "default": true,
    }
  ]
}

Trying to loop sort add where “default”: true. Through the browser the file is in the local folder. If you write json in the js file, everything works. The js code:

function loadJsonData() {
var cc = here's the json code

    var myArray = cc.res;
    var idToLookFor = true;

    var addrs = myArray
      .filter(function (item) {
        return item.default === idToLookFor;
      })
      .map(function (elem) {
        return elem.add;
      })
      .join(",");
console.log(addrs);
};

But I want to do it via file selection or textarea. I have tried all the options and I get undefined everywhere. Here are some variants I have tried:

const el = document.getElementById('benderform').addEventListener('submit', submitForm);
function submitForm(event) {
    event.preventDefault();
    let formData = new FormData(event.target);
    let obj = {};
    formData.forEach((value, key) => obj[key] = value);
    console.log(obj);
var idToLookFor = true;
    var addrs = obj.filter(function (item) {
        return item.default === idToLookFor;
      })
      .map(function (elem) {
        return elem.add;
      })
      .join(",");
      console.log(addrs);
    console.log('ok');
}</script>
<form id="benderform">
  <input name="name" value="Bender">
  <input type="submit" value="TEST">
  </form>
function loadJsonData() {
var cc = document.getElementById("dropdown").value;
    var myArray = cc.res;
    var idToLookFor = true;   
    var addrs = myArray.filter(function (item) {
        return item.default === idToLookFor; }).map(function (elem) {
        return elem.add;}).join(",");
    console.log(addrs);
};

When using the command:

$.getJSON('filename.json', function(data) {

It returns: from origin ‘null’ has been blocked by CORS policy:

Is there any way to get this data without using the server and adding the json text directly to the js file?


阅读 65

收藏
2023-12-21

共1个答案

小能豆

When working with local JSON files in a browser, you might encounter CORS (Cross-Origin Resource Sharing) issues, especially when trying to load JSON files directly from the file system. Browsers have security measures in place that restrict making requests to local files from web pages.

To handle this situation, you can use alternative methods to load JSON data:

  1. Use fetch API with local server: Set up a simple local server (e.g., using Node.js and http-server or Python with http.server) in the directory containing your HTML and JSON files. Then, use the fetch API to load the JSON file. This approach avoids CORS issues.

Example using Node.js:

npm install -g http-server http-server

Example JavaScript:

fetch('http://localhost:8080/yourfile.json') .then(response => response.json()) .then(data => { // Process your JSON data here console.log(data); }) .catch(error => console.error('Error:', error));

  1. Use File Input Element: Allow users to choose a local file using the file input element (<input type="file">). Once the user selects the file, you can read its content using FileReader.

Example HTML:

<input type="file" id="fileInput" /> <button onclick="loadJsonData()">Load JSON</button>

Example JavaScript:

```
function loadJsonData() {
const fileInput = document.getElementById(‘fileInput’);
const file = fileInput.files[0];

 if (file) {
   const reader = new FileReader();
   reader.onload = function (e) {
     const jsonData = JSON.parse(e.target.result);
     console.log(jsonData);
     // Process your JSON data here
   };
   reader.readAsText(file);
 }

}
```

Choose the method that best fits your requirements and application architecture. Keep in mind that loading files directly from the local file system might not work in all scenarios due to security restrictions imposed by browsers.

2023-12-21