19

how do i convert a json object to a string

i want to insert a json object to a mysql DB

user401000
  • 217
  • 1
  • 3
  • 6

3 Answers3

26

You might be interested in json_encode().

On the other hand if you already got something json encoded then it already is a string and you can simply store it as-is in the database.

VolkerK
  • 95,432
  • 20
  • 163
  • 226
  • Old post but, can you tell me why I get these `\n` instead of `new line` in my string? I need to `json_encode($data)` to store to Redis (as string). And later `json_decode($string)` to get my values from a json.. – nclsvh Jan 13 '16 at 19:43
  • 1
    That's just how a linebreak is encoded in JSON (and javascript). When it gets parsed the `\n` "becomes" a linebreak again, see https://jsfiddle.net/tafodvn5/ – VolkerK Jan 14 '16 at 00:15
  • Yep, found out the hard way late at night :p Anyway thanks for the reply! – nclsvh Jan 14 '16 at 11:38
10

JSON itself is a string. People use json_encode() and json_decode() to convert objects/arrays of PHP to string and back to objects/arrays.

Ramesh Seera
  • 171
  • 1
  • 4
-2

$array = json_decode($json,true); $string = implode(",",$array);

Now you can save this string in db as text.

  • 1
    This isn't really adding anything to the question that's not yet been added. Also, please use code formatting to make code more readable. – Simon S. Mar 30 '21 at 11:27