Norman
Norman

Reputation: 6365

Convert a string of comma separated values into a JSON array

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

Answers (6)

ncubica
ncubica

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

coDe murDerer
coDe murDerer

Reputation: 1876

Jquery : For Array,

var array = myString.split(',');

For String,

var string = JSON.stringify(array);

Upvotes: 0

Jean-Karim Bockstael
Jean-Karim Bockstael

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

pid
pid

Reputation: 11597

Did you explode() the PHP string before encoding it?

json_encode(explode(',', $string));

Upvotes: 1

Ende Neu
Ende Neu

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"]

Example in sandbox.

Upvotes: 8

Jite
Jite

Reputation: 5847

explode (Docs) the string (to make it an array) and then convert it to json with the json_encode function.

Upvotes: 1

Related Questions