22

How do I convert a JSON object to a string?

I want to insert a JSON object into a mysql DB.

4
  • 5
    Exactly what is a "json object" in php? Commented Jul 31, 2010 at 10:42
  • 7
    the output of json_encode is a string! what json object are you talking about? Commented Jul 31, 2010 at 10:53
  • Are you facing any problem with the PHP part or with the MySQL part? What have you tried to resolve the problem? Where are you stuck? Commented May 22, 2024 at 12:58
  • JSON is a serialization format, so it's a string already. JSON (the format) is sometimes confused with JavaScript (the language), thus the use of the incorrect term "JSON object", but it's unclear what that can possibly mean in the context of PHP. Commented May 22, 2024 at 13:07

2 Answers 2

29

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.

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

3 Comments

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..
That's just how a linebreak is encoded in JSON (and javascript). When it gets parsed the \n "becomes" a linebreak again, see jsfiddle.net/tafodvn5
Yep, found out the hard way late at night :p Anyway thanks for the reply!
11

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.

2 Comments

@MihaiGalan That answer is misleading. JSON is a format, but its data is stored in a string.

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.