簡體   English   中英

將json文件中的值替換為文本文件中的值

[英]Replace values from json file with ones in a text file

我有2個文件,我想用新文件中的值替換JSON文件中的所有值。

我的JSON格式如下:

{
 "id": 1,
 "name": "",
 "code": 9.3
 },

 {
 "id": 2,
 "name": "Test",
 "code": 5.0
 },

我的.txt文件是:

1 - 9.9
2 - 3.4

等等

因此,對於json文件中的所有id等於文本文件中的第一個數字,我想將“ code”替換為.txt文件中該行中的第二個數字。

->從文件中讀取JSON值:-

    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader("input1.json"));
    JSONObject jsonObject = (JSONObject) obj;
    String id= (String) jsonObject.get("id");

->從文本文件中讀取輸入值:-

    FileReader fr=new FileReader(new File(input2.txt));
    BufferedReader br = new BufferedReader(fr); 
    String s; 
    while((s = br.readLine()) != null) { 
      String[] strArr=s.split("-"); //split each element of input text file to get id and value individually
                .
                .
     }

->比較ID並將更新的值寫入新的JSON文件

       JSONObject objWr = new JSONObject();
       if(id.equals(strArr[0].trim())){
       objWr.put("id", id);
       objWr.put("code", strArr[1]); //replace code with 2nd element in String[] from txt file
       }
       FileWriter fw= new FileWriter("output.json");
       fw.write(objWr.toJSONString());
       fw.flush();

注意:-在很多地方,我都錯過了關閉I / O流以及將try-catch塊放入其中的過程,希望您幫忙填寫。

暫無
暫無

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

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