【问题标题】:append json key value pair to a .json file Titanium将 json 键值对附加到 .json 文件 Titanium
【发布时间】:2013-10-15 06:18:26
【问题描述】:

我有一个名为 wordsAndMeaning.json 的 .json 文件

{
    "words" : [
        {   
            "name" : "Apple",
            "meaning" : "A fruit"
        },
        {
            "name" : "Truck",
            "meaning" : "A heavy vehicle"
        },
        {
            "name" : "Zebra",
            "meaning" : "An animal"
        },
        {
            "name" : "Rock",
            "meaning" : "A music Genre"
        }
    ]
}

我的窗口中有两个文本字段,其中包含名称和名称的含义以及一个提交按钮。

我想要做的是在我填写 textFields 并单击 Submit(即 addEventListener)后,我希望输入的数据作为新的键值对附加到上述 wordsAndMeanings.json 文件中。

资源目录中存在wordsandMeanings.json文件,我使用fileSystem来实现。

我是 JSON 概念的新手。如此详细的代码解释将不胜感激。我正在 Titanium 中执行此任务。

我将把我的整个 app.js 代码放在下面

var window = Ti.UI.createWindow();

var view1 = Titanium.UI.createView({
    backgroundcolor:'21DCEE'
});
var view2 = Titanium.UI.createView({});

var textName = Titanium.UI.createTextField({
    top:100,
    left:50,
    height:50,
    width:150,
    borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
    hintText:'Enter the word'
});

var textMeaning = Titanium.UI.createTextField({
    top: 200,
    left:50,
    width:150,
    height:50,
    borderStyle: Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
    hintText:'Enter its meaning'
});

var submit = Titanium.UI.createButton({
    top:300,
    left:100,
    title:'Submit'
});

var tableView = Ti.UI.createTableView();
var tableData = [];
var fileName = 'wordsAndMeanings.json';
var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, fileName); 
var preParseData = file.read();
var response = JSON.parse(preParseData);
Ti.API.info(response.words.length);
for(var i = 0; i < response.words.length ; i++){
    word = response.words[i];
    row = Ti.UI.createTableViewRow({
        height : '60dp'
    });
    nameLabel = Ti.UI.createLabel({
        text: word.name,
        font: { fontSize:'24dp', fontWeight:'bold'},
        height:'auto',
        left:'10dp',
        color:'#000',
        touchEnabled : false
    });
    row.add(nameLabel);
    tableData.push(row);
    tableView.setData(tableData);
}

var add = Titanium.UI.createButton({
    title: 'Add',
    top: 150,
    left: 50
});

add.addEventListener('click',function(e){
    window2 = Titanium.UI.createWindow({
        backgroundColor:'8FD2ED'
    });

    submit.addEventListener('click', function(e){
        //response.words.push({"name" : "abc", "meaning" : "alphabets"});
        //Ti.API.info(typeof(textName.value));
        //var one = JSON.parse(textName.value);
        //Ti.API.info(one);
        var obj = eval("(textName.value)");
        Ti.API.info(obj);
        //var file2 = Titanium.FileSystem.getFile(Titanium.FileSystem.resourcesDirectory,'wordsAndMeanings.json');
        //file2.write()
    });


    window2.open();
    window2.add(view2);
    view2.add(textName);
    view2.add(textMeaning);
    view2.add(submit);
});
window.open();
window.add(view1);
view1.add(tableView);
view1.add(add);

【问题讨论】:

    标签: javascript json titanium appcelerator


    【解决方案1】:

    您可以使用write method 在 Titanium 中写入文件。在执行此操作之前,您应该了解Titanium File System

    您还应该将声明 var obj = eval("(textName.value)"); 更改为 var obj = eval("(" + textName.value + ")");

    【讨论】:

      【解决方案2】:

      阅读 @Anand 链接到的文档后,您会发现无法在 resourcesDirectory 中写入。您可以将新文件保存在 applicationDataDirectory 中,然后从该文件加载。

      由于您已经在字典中解析数据 (var response = JSON.parse(preParseData);),我将按照您在提交事件侦听器 (//response.words.push({"name" : "abc", "meaning" : "alphabets"});) 中完成的方式添加新数据,最后添加 stringify响应字典来保存它。

      1)所以读取并解析json:

      var fileName = 'wordsAndMeanings.json';
      var file = Ti.Filesystem.getFile(Ti.Filesystem.resourcesDirectory, fileName); 
      var preParseData = file.read().text; // file.read() will return the blob. file.read().text is what you want
      var response = JSON.parse(preParseData);
      

      2) 在提交点击和追加数据时获取字段数据

      submit.addEventListener(click, function(e) {
       var userTextMeaning = textMeaning.value; // Read value property of both fields
       var userTextName = textName.value;
       response.words.push({"name" : userTextName, "meaning" : userTextMeaning}); // Push the new data to response list
      }
      

      3) 字符串化并保存在applicationDataDirectory中

      var fileName = 'wordsAndMeanings.json';
      var file = Ti.Filesystem.getFile(Ti.Filesystem.applicationDataDirectory, fileName); 
      var json = JSON.stringify(response);
      file.write(json)
      

      【讨论】:

      • 根据 [link] (wiki.appcelerator.org/display/guides/…) resourcesDirectory 支持在 SIMULATOR/EMULATOR 上读写。我正在模拟器上工作,而不是在实际设备上工作。而且我还需要将 文本字段 数据(即 textName 和 textMeaning)写入 .json 文件,如何提取该数据并将其作为新的键值对写入文件?跨度>
      【解决方案3】:

      使用Titanium.App.Properties() 代替文件系统会好很多。您可以使用以下方法轻松存储和检索整个对象:

      • Ti.App.Properties.getObject('propertyName', defaultValue); - 属性不存在时返回第二个参数。
      • Ti.App.Properties.setObject('propertyName', value);

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-05-21
        • 1970-01-01
        • 2017-10-17
        • 2020-04-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多