2014-12-23 46 views
0

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

我的JSON格式是一樣的東西:

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

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

我的.txt文件是:

1 - 9.9 
2 - 3.4 

所以在JSON文件等於在第一號的所有IDS我想用文本文件中的第二個數字替換「code」,該文件位於.txt文件中。

+2

什麼編程語言?例如,這在Python中是微不足道的。 –

+0

使用哪種編程語言? – Backtrack

+0

JSON文件應該包含一個數組。應該有'''圍繞整個事情。 – Barmar

回答

0

- >閱讀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 
       . 
       . 
    } 

- >比較IDS和寫入更新值到新的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塊,我將離開您填寫希望這有助於。