簡體   English   中英

使用javascript更新json文件

[英]Use javascript to update a json file

我想通過說我知道我在做什么並不理想來作為序言。 有了這個:

我需要通過javascript更新JSON文件中的數據。 這是目前的JSON文件:

{
"nextid" : 3,
"ingredients" : [
{
    "id": 1,
    "name": "onion",
    "kilojoules": 180,
    "quantity": 1,
    "measurement": "whole",
    "nutrition": [
        {"value": "Fat Total", "quantity": 110},
        {"value": "Saturated Fat", "quantity": 46},
        {"value": "Sodium", "quantity": 4},
        {"value": "Carbohydrates Total", "quantity": 10000},
        {"value": "Sugar", "quantity": 5000},
        {"value": "Fibre", "quantity": 2000},
        {"value": "Proten", "quantity": 1000}
    ]},

{
    "id" : 2,
    "name": "carrot",
    "kilojoules": 56,
    "quantity": 1,
    "measurement": "whole",
    "nutrition": [
        {"value": "Fat Total", "quantity": 66},
        {"value": "Saturated Fat", "quantity": 11},
        {"value": "Sodium", "quantity": 26},
        {"value": "Carbohydrates Total", "quantity": 3000},
        {"value": "Sugar", "quantity": 2000},
        {"value": "Fibre", "quantity": 1000},
        {"value": "Proten", "quantity": 279}
    ]}
]

}

現在讓我們說我想編輯胡蘿卜對象。 我在我的html頁面上構建了一個更新的胡蘿卜對象,並將其作為javascript中的對象。 我需要做些什么才能使用我的編輯來更新源json?

就像我之前說過的,我知道這不太理想。 我應該使用一個數據庫來存儲和操作數據,但我現在已經把我的床鋪了,我必須讓它工作,不管它有多大可能會讓你感到畏縮。

研究告訴我,我將需要在服務器端使用PHP或ASP來收集javascript傳遞給它的參數,但我不知道從哪里開始。

我在visual studio 2012工作,項目的參數禁止我使用插件。 NuGet代碼庫是的,但沒有插件。 在此基礎上,我認為這意味着我不能使用PHP。 我的想法是否正確?

注意:是的,它用於分配,但是更改json文件超出了要求的范圍。 能夠動態處理json數據對於項目來說已經足夠了,我真的很想能夠放回一些。

提前致謝

編輯:可能也應該分享這個。 這是打開json文件的javascript。 打開的結果存儲在名為ingJson的腳本范圍變量中。

function downloadIngredients() {
$(document).ready(function () {
    $.getJSON("/data/ingredientsInfo.js", function (result) {
        try
        {
            ingJson = result;
            ingredients = result.ingredients;
            ingredients.sort(orderByNameAscending);
            buildListBox(ingredients);
        }
        catch (err) {
            alert(err.message);
        }
    });
});
}

要編輯JSON文件:

  1. 用php 打開文件
  2. 將內容發送到瀏覽器(只需將其作為字符串轉儲到腳本標記中的變量中)
  3. 使用JavaScript 解析 JSON( onload - >從腳本標記中獲取字符串)
  4. 編輯對象
  5. 再次轉換為JSON字符串
  6. 發送php
  7. php覆蓋該文件。

遺憾的是你不能直接在php中編輯文件,這樣就不需要執行步驟2-6了,你只需在php中解析編輯編碼 JSON。

編輯 :由於您似乎已經在JavaScript中擁有數據,因此會考慮步驟1-3。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM