从json删除数据

时间:2019-03-19 11:54:01

标签: javascript php jquery html arrays

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

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

@edit 我添加了一个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函数从输入文件中保存 如何删除数组中的一个对象?等等,我想删除索引为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');

1 个答案:

答案 0 :(得分:0)

我认为您正在寻找的是

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