Encode value to JSON as a number

Posted on 2010-01-04
Last Modified: 2012-05-08

I'm fetching rows of data from a mysql database, in order to return it as a JSON object later on. Looks like this:

  $rows = array();
  $result = mysql_query("SELECT * FROM mytable");
  while ($row = mysql_fetch_assoc($result)) {
      $rows[] = $row;

  echo json_encode($rows);

one of my fields in the database is of type DOUBLE. But when I look out the output JSON object, that key/value pair is encoded as a string (has quotes around the value):

  "average": "1.33"

but it should be:

  "average": 1.33

what's the right way to do that?

Question by:DJ_AM_Juicebox
    1 Comment
    LVL 13

    Accepted Solution

    don't know any better way, but this can be tricky.

    ##  echo json_encode($rows);
    echo preg_replace( '/(":\s?)"(\d+\.\d+)"/', "$1$2", json_encode($rows) );

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    How to run any project with ease

    Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
    - Combine task lists, docs, spreadsheets, and chat in one
    - View and edit from mobile/offline
    - Cut down on emails

    A colleague recently asked me about how to give his client a small part of the web site that could be completely under the client's control.  Since I have done this sort of thing before to add emergency banners to a web site, I decided I would creat…
    Both Easy and Powerful How easy is PHP? (  Very easy.  It has been described as "a programming language even my grandmother can use." How powerful is PHP?  http://en.wikiped…
    The viewer will learn how to count occurrences of each item in an array.
    The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now