正则表达式:如何将CSV数据转换为JSON数组?

时间:2012-06-10 13:22:56

标签: regex json vim csv sublimetext2

如何使用正则表达式将csv字符串转换为JSON数组?

我正在尝试将正则表达式用于文本编辑器,如Vim或Sublime Text,而不是编程语言。仅供参考,Sublime Text使用Boost syntax

如果我有一组像这样的csv字符串:

"tag1, tag2, tag3"

上面的字符串应格式如下:

["tag1", "tag2", "tag3"]

(添加了整个内容的解释......)

csv字符串位于内容的中间,如下所示:

...
{"url":"http://osxdaily.com/2007/0ge5/02/quickly-encrypt-a-file-with-openssl",
 "user":"user01","tag_string":"openssl,encrypt",
 "created_at":"2011/04/19 05:49:26 +0000",
 "title":"Quickly encrypt a file with OpenSSL"},  
{"url":"http://staticimport.blogspot.com","user":"user02",
 "tag_string":"command,line,developer,tools,osx",
 "created_at":"2011/04/19 05:42:13 +0000","title":"Mac OS X Lion Command Line Developer Tools staticimport"},    
{"url":"https://developer.apple.com/downloads/index.action",
 "user":"user_01","tag_string":"ios,development,download",
 "created_at":"2011/04/19 04:47:26 +0000","title":"Apple Developer Download Center"}
...

tag_string 是要转换为JSON数组的csv字符串。

1 个答案:

答案 0 :(得分:4)

在Vim,三遍:

:s/,\s*/", "/g
:s/^/[
:s/$/]