將乙個html標記 轉 json串

2021-06-09 05:25:22 字數 2479 閱讀 6582

/**

* 將乙個html標記 轉 json串

* @param html 要處理的html標籤。html串必須有且僅有乙個根節點。

* @param indent_str_count 起始縮排符個數

* @param indent_str 縮排符,預設tab鍵

* @param indent 縮排物件

* @return json

* ,

* "content": ["標籤內容" | json | [json陣列]]

* }

* 出錯返回結果:

* @test 巢狀(nested):html2json("詳細結構

原始郵件

詳細結構

") * @test 同級(sibling):html2json("詳細結構

原始郵件

") * @create xiaolong8 @ 2012-6-7 16:30:48

* @modify [content欄位的文字新增對"進行替換為\"的轉義形式] by [堅] @ [2012-6-8 9:03:36]

* @modify [content欄位新增:對標籤內容若仍為html標籤,則繼續轉json] by [堅] @ [2012-6-8 9:22:32]

* @modify [新增json串縮排顯示] by [堅] @ [2012-6-8 11:54:27]

* @modify [屬性組(attrs)json生成時,按空格分離屬性到陣列(.split(/\s+/))的方式改為按正則匹配到陣列(.match(/\w+=(?:"(?:[^"]|(?:\"))+?"|'(?:[^']|(?:\'))+?')/g);)的方式] by [堅] @ [2023年6月11日11:51:56]

* @modify [新增對使用者傳入的html串做根/巢狀標籤和同級標籤的處理] by [堅] @ [2012-6-11 17:25:07]

* @modify [log] by [user] @ [time]

* @todo: input img 這類單行標籤未處理

*/function html2json(html, indent_str_count, indent_str, indent)

string.prototype.trim = string.prototype.trim ||

function();

html = html.trim();

/// 同級標籤解析,若match後長度等於1,說明不是同級標籤 */

htmlels = html.match(/<(\w+)([^>]*)>(.*?)<\/\1>/gi);

if (!htmlels)

/// 設定各種預設值

// 預設縮排1個字元

indent_str_count = indent_str_count || 1;

// 預設縮排字元為tab鍵

indent_str = indent_str || "\t";

// 縮排物件(共用)

indent = indent || count

* @return count個縮排字元

* @test

* @create 堅 @ 2012-6-8 10:26:32

* @modify [log] by [user] @ [time]

*/"factory": function(count)

return this.strings[index];

},"getindentstr": function()

};if (htmlels.length > 1) ;

}var elsjson = "["

for (var i = 0; ; i++)

elsjson += ", ";

}elsjson += indent.factory(indent_str_count - 1) + "]";

return elsjson;

} else if (htmlels.length == 1)

attrsjson += ", \n";

}attrsjson += indent.factory(indent_str_count)+ "}";

}return attrsjson;

})() + ", \n" +

indent.factory(indent_str_count) + "\"" + html_tag_content + "\": " +

html2json(content, indent_str_count + 1, indent.getindentstr(), indent) + "\n" +

indent.factory(indent_str_count-1) + "}";

return json;

}}

JSON轉實體的乙個小坑

剛入職的小碼農乙個,開個部落格記錄一下平時遇到的一些問題解決方法 小經驗技巧 和 新思路新想法quq 今天除錯了半天的乙個問題關於json轉實體 json 轉實體類a,a中欄位不為string 時,如 integer,bigdecimal 時,json中的該字段值為 或根本沒有put進去時,轉換後為...

將json串存入資料庫的乙個欄位裡

這裡要注意單引號在sql語句中是用於表示字串引用的 通常在json字串中會有單引號,或者雙引號用來表示字串引用。通常雙引號才是規範的。那麼將json字串本身原封不動地存進資料庫時,要注意將json字串中的單引號進行轉義。即再新增乙個 在json字串的單引號前面。這樣sql程式才不會把json字串中的...

js解析JSON串的乙個小坑

今天寫ajax時,像平常一樣用jsonobject新增key,value,然後tostring返回到前台 在success方法中使用data.key並不能拿出來值,請教了公司的前端之後才明白,json在前台 有兩種方式來取資料 1.json.parse jsonstr key 2.json.pars...