2017-10-09 565 views
0

幫我理解sed.I的語法,刪除了單引號,但代碼仍然不起作用。TCL腳本中的sed命令

set id [open file.txt] 
# send the request, get a lot of data 
set tok [::http::geturl "http://example.com"-channel $id] 
# cut out the necessary data between two words 
exec sed s/{"data1":\(.*\)/data2\1/ $id 
close $id 
set ir [open file.txt] 
set phone [read $ir] 
close $ir 
puts $phone 

的問題是,我從以下那種

{"id":3876,"form":"index","time":21,"data":"2529423","service":"Atere","response":"WAIT"} 

護膝查詢得到的數據是語言的語法的元素,我需要削減完全之間的值字和大括號。如何在腳本中實現這一點。

+0

44問/當在這裏搜索爲'使用sed [tcl]'。有些看起來很有希望。最好也更新你的Q以顯示需要的輸出。祝你好運。 – shellter

回答

1

你的代碼是相當混亂,因爲(a)您正在傳遞的文件句柄sed命令。這是行不通的。 (b)您將輸入通道傳遞給http而不是輸出通道(嘗試打開文件進行寫入)。

有關基本問題。 如果您正在接收基本的JSON數據,如圖所示。

a)您可以使用JSON解析器:tcllib's json module

二)將其轉換爲形式的Tcl可以作爲字典

# Assuming the JSON data is in the $data variable, and there's no 
# other data present. This also assumes the data is very basic 
# there are no embedded commas. Many assumptions means this 
# code is likely to break in the future. A JSON parser would 
# be a better choice. 
set data "\{" 
append data {"id":3876,"form":"index","time":21,"data":"2529423","service":"Atere","response":"WAIT"} 
append data "\}" 
regsub -all {[{}:",]} $data { } data 
set mydatadict $data 
puts [dict get $mydatadict id] 

編輯解析:

對於HTTP處理:

set tok [::http::geturl "http://example.com"] 
set data [::http::data $tok] 
::http::cleanup $tok 
+0

是的,在另一個資源上,我也指出了這一點。感謝你的回答。我怎樣才能從文件中添加文本到字典?或者是直接從http查詢更好? – Lefeofan

+0

非常感謝!我根據你的建議做了一切工作。 – Lefeofan

+0

不添加虛假空白的很多可能的替代方法:'設置數據[正則表達式 - 所有-inline {[^「{}:,] +} $的數據。'坯料甭管'dict'命令,當然,需要注意的是,如果該鍵或值有空格在他們需要更多的聰明。 –