Reputation: 6365
How can I convert a string of comma separated values into valid json, using either php or jquery?
The comma separated strings are stored in a database and are like this:
Singapore,Andora,Australia
The output I need is like this: ["Singapore","Andora","Australia"]
I tried using php's json_encode
on the string, but that does not render json the way I need it. It does this "Singapore,Andora,Australia"
Any way I could get this the way I want it?
Upvotes: 2
Views: 12054
Reputation: 8475
Simple as:
var data = "Singapore,Andora,Australia".split(",");
console.log(data); //["Singapore", "Andora", "Australia"]
thats is gonna return an array with three values
Upvotes: 0
Reputation: 1876
Jquery : For Array,
var array = myString.split(',');
For String,
var string = JSON.stringify(array);
Upvotes: 0
Reputation: 1405
Solution in 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);
Solution in JavaScript/jQuery:
var encoded = JSON.stringify("Singapore,Andora,Australia".split(","));
Upvotes: 1
Reputation: 11597
Did you explode()
the PHP string before encoding it?
json_encode(explode(',', $string));
Upvotes: 1
Reputation: 15773
Split the string and then encode the array:
$str = "Singapore,Andora,Australia";
$splitted = explode(",", $str);
print_r(json_encode($splitted));
// output : ["Singapore","Andora","Australia"]
Upvotes: 8