[英]Convert a string of comma separated values into a JSON array
如何使用php或jquery將逗號分隔的字符串轉換為有效的json?
逗號分隔的字符串存儲在數據庫中,如下所示:
Singapore,Andora,Australia
我需要的輸出是這樣的: ["Singapore","Andora","Australia"]
我嘗試在字符串上使用php的json_encode
,但這並不能按照我需要的方式呈現json。 這樣做是"Singapore,Andora,Australia"
我能以我想要的方式得到它嗎?
分割字符串,然后對數組進行編碼:
$str = "Singapore,Andora,Australia";
$splitted = explode(",", $str);
print_r(json_encode($splitted));
// output : ["Singapore","Andora","Australia"]
沙箱中的示例 。
explode
( 文檔 )字符串(使其成為數組),然后使用json_encode
函數將其轉換為json。
在編碼之前,您是否explode()
了PHP字符串?
json_encode(explode(',', $string));
PHP解決方案:
$raw = "Singapore,Andora,Australia";
// Use explode() to parse the string into an array
$parsed = explode(",", $raw);
// Encode the resulting array as JSON
$encoded = json_encode($parsed);
JavaScript / jQuery中的解決方案:
var encoded = JSON.stringify("Singapore,Andora,Australia".split(","));
jQuery:對於數組,
var array = myString.split(',');
對於字符串,
var string = JSON.stringify(array);
簡單為:
var data = "Singapore,Andora,Australia".split(",");
console.log(data); //["Singapore", "Andora", "Australia"]
多數民眾贊成在返回三個值的數組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.