2

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?

1
  • 2
    "Singapore,Andora,Australia".split(',') will return you an array of strings Commented Sep 8, 2014 at 7:57

6 Answers 6

8

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

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

Comments

1

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(","));

Comments

0

Jquery : For Array,

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

For String,

var string = JSON.stringify(array);

Comments

0

Simple as:

var data = "Singapore,Andora,Australia".split(",");
console.log(data); //["Singapore", "Andora", "Australia"]

thats is gonna return an array with three values

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.