【问题标题】:Delete data from json从 json 中删除数据
【发布时间】:2019-03-19 11:54:00
【问题描述】:

我在从我的 json 文件中删除对象时遇到问题:

{
    "data": [{
        "index": "1",
        "part": "15",
        "dueDate": "2019-03-19"
    }]
}, {
    "data": [{
        "index": "2",
        "part": "22",
        "dueDate": "2019-03-19"
    }]
},

@编辑 我添加了一个javascript代码。函数 getTasks 在 html 站点中显示此 json 文件。所以,也许在这里我应该做出改变。

   var todos = new Array();
var todo_index = 0;
window.onload = init;

function init() {
    var submitButton = document.getElementById("submit");
    submitButton.onclick = getFormData;
    getTodoData();
}

function getTodoData() {
    function request(method, url, data=null) {
        return new Promise((resolve, reject)=> {
            const xhr = new XMLHttpRequest;
            xhr.timeout = 2000;
            //xhr.responseType = 'json';
            xhr.onreadystatechange = (e) => {
                if(xhr.readyState === 4){
                    xhr.status === 200 ? resolve(xhr.response) : reject(xhr.status)
                }
            }
            xhr.ontimeout = () => reject('timeout');
            xhr.open(method, url, true);

            if(method.toString().toLowerCase() === 'get') {
                xhr.send(data)
            } else {
                xhr.setRequestHeader('Accept','application/json');
                xhr.setRequestHeader('Content-type', 'application/json');
                xhr.send(data)
            }
        })
    }
async function getTasks(){
  const task = await request('GET', '/WebService/todo.json');
   document.getElementById("todoList").innerHTML=task
}
getTasks()
}

function parseTodoItems(todoJSON) {
    if (todoJSON == null || todoJSON.trim() == "") {
        return;
    }
    var todoArray = JSON.parse(todoJSON);
    if (todoArray.length == 0) {
        console.log("Error: Array is empty!");
        return;
    }
    for (var i = 0; i < todoArray.length; i++) {
        var todoItem = todoArray[i];
        todos.push(todoItem);
    }
}

function checkInputText(value, msg) {
    if (value == null || value == "") {
        alert(msg);
        return true;
    }
    return false;
}        
function Todo(index, part) {
    this.index = index;
    this.part = part;
}



function addTodosToPage() {
  var table = document.getElementById("todoList");
  var tr = document.createElement("tr");
  var index = document.getElementById('index').value;
  var part = document.getElementById('part').value;
  tr.innerHTML = "<td>" + index + "</td><td>" + part + "</td>";
  table.appendChild(tr);


  todo_index++;


  tr.id = "todo-" + todo_index;

  var index = document.getElementById('index').value;
  var part = document.getElementById('part').value;

  tr.innerHTML = "\
  <td><input name='select-row' type='checkbox' value='" + todo_index + "'></td>\
  <td>" + index + "</td>\
  <td>" + part + "</td>\
  <td><button onclick='removeTodo(" + todo_index + ");'>x</button></td>";
  table.appendChild(tr);
}

function getFormData() {
    var index = document.getElementById("index").value;


    var part = document.getElementById("part").value;


    console.log("Index: " + index + " part: "+ part);
    var todoItem = new Todo(index, part);
    todos.push(todoItem);
    addTodosToPage(todoItem);
    saveTodoData();

}

function checkInputText(value, msg) {
    if (value == null || value == "") {
        alert(msg);
        return true;
    }
    return false;
}        

function saveTodoData() {
    var todoJSON = JSON.stringify(todos);
    var request = new XMLHttpRequest();
    var URL = "save.php?data=" + encodeURI(todoJSON);
    request.open("GET", URL);
    request.setRequestHeader("Content-Type",
                             "text/plain;charset=UTF-8");
    request.send();
}
function removeTodo(index) {

  var row = document.getElementById('todo-' + index);


  if (row) {

    row.parentNode.removeChild(row);
  }


  todo_index--;
}


function toggleSelection(checkbox) {

  var rowsToSelect = document.querySelectorAll('input[name=select-row]');

  for (var i = 0; i < rowsToSelect.length; i++) {

    rowsToSelect[i].checked = checkbox.checked;
  }
}

function removeSelectedTodos() {

  var rowsToRemove = document.querySelectorAll('input[name=select-row]:checked');

  for (var i = 0; i < rowsToRemove.length; i++) {

    removeTodo(rowsToRemove[i].value);
  }
}



function setselection(){
  var project = document.getElementById('todoList').value;
  document.cookie = 'todotabel=' + project;
}



function getselection(){
  var name = 'todotabela=';
  var x = document.cookie.split(';');
  var i = 0, c = 0;
  for(i = 0; i < x.length; i++) {
    c = x[i];
    while (c.charAt(0) === ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(selectedProject) === 0) {
      return c.substring(name.length, c.length);
    }
  } return '';
}

function remove() {

  var arr = [];
  var obj = {
    'index': document.getElementById("index").value
  };
  for (var i = arr.length - 1; i >= 0; i--) {
    if (arr[i]['index'] === obj['index']) {
      arr.splice(i, 1);
    }
  }
  localStorage.removeItem("user", JSON.stringify(arr));

}

function appendLocalStorage(keys, data) {
  var old = localStorage.getItem(index);
  if (old === null) old = "";
  localStorage.setItem(index, old + data);
}

function addTo() {
  var arr = [];
  var obj = {
    'index': document.getElementById("index").value,
    'part': document.getElementById("part").value,

  };

  if (!arr.some(e => e['index'] == obj['index'])) {

    arr.push(obj);
  } else {
    arr[arr.map((e, i) => [i, e]).filter(e => e[1]['index'] == obj['index'])[0][0]] = obj;
  }
  appendLocalStorage("user", JSON.stringify(arr));
  alert(localStorage.getItem("user"));
}

此数据由 php 和 javascript 函数从输入文件中保存 如何删除数组中的一个对象?等等我想用 index:2 删除对象,我需要通过 html 中的按钮删除它。我该怎么做?

我的 php 文件:

$unsafe_json = json_decode($_GET["data"], true);
if (!is_array($unsafe_json)) {
    die('Error save');
}
$safe_json = ['data' => []];
$values    = ['index', 'part', 'dueDate'];
foreach ($unsafe_json as $unsafe_todo) {
    $safe_todo = [];
    foreach ($values as $value) {
        if (isset($unsafe_todo[$value]) && is_string($unsafe_todo[$value])) {
            $safe_todo[$value] = filter_var($unsafe_todo[$value], FILTER_SANITIZE_STRING);
        } else {
            $safe_todo[$value] = false;
        }
    }
     *  /
    $safe_json['data'][] = $safe_todo;
}
$file = fopen("todo.json", "a");
fwrite($file, '' . json_encode($safe_json) . ',');
fclose($file);
$data = file_get_contents('todo.json');

【问题讨论】:

  • 您的第一个包含 json 的 sn-p 似乎无效。它缺少最外面的[]
  • @Taplar 你能告诉我,我该如何解决它?
  • 你从哪里得到 json?
  • @Andreas 我通过输入将数据添加到 html 中的输入来创建他,然后在 javascript 中创建。
  • @Tom 你想用什么语言来做 php 或 js?

标签: javascript php jquery html arrays


【解决方案1】:

我认为你正在寻找的是

unset($OBJECT['INDEX']);

你可以遍历你的 JSON,当你匹配你的条件时,你可以调用 PHP 的 unset() 方法来删​​除索引

*更新 用 php 删除的代码示例

$json_decoded = json_decode($json_encoded, true);
foreach ($json_decoded as $i => $object)
    if ($object['data']['index'] == 2)
        unset($json_decoded[$i]);

【讨论】:

  • 是的,我认为这可能会有所帮助。你能告诉我如何在我的代码中实现它吗?
  • 我已经更新了我的答案,希望这是你想要的,你可以更改变量名以匹配你的,它应该可以工作
  • 谢谢,但我必须能够删除任何索引,我有一个按钮和复选框。我在 html 站点中有一个删除,但我需要可以同时从 json 文件中删除
猜你喜欢
  • 2013-11-23
  • 2017-12-14
  • 2015-03-13
  • 2021-01-06
  • 2013-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多