convert mysql result to json with correct types

后端 未结 4 441
南方客
南方客 2020-12-11 20:14

I know how to get a mysql-row and convert it to json:

$row = mysqli_fetch_assoc(mysqli_query($db, \"SELECT * FROM table WHERE id=1\"));
echo json_encode($row         


        
4条回答
  •  北海茫月
    2020-12-11 20:54

    If you're simply trying to make sure that your values are operable with respect to their type, you need to first cast their type correctly.

    Unless you need them server-side, I would just pass-on the json directly to the front-end and do the work there.

    In Javascript, you could make an attempt at casting the numbers like so:

    function tryNumber(string){
    
        return !isNaN( parseInt(string) ) ? parseInt(string) : string;
    
    }
    
    function tryDate(string){
    
        return !isNaN( new Date(string).getTime() ) ? new Date(string) : string;
    
    }
    
    tryNumber('foo'); // "hello"
    tryNumber('24'); // 24
    tryDate('bar'); // "bar"
    tryDate('December 17, 1995'); // "Sun Dec 17 1995 00:00:00 GMT+0000 (GMT)"
    

    These two lines attempt to cast the values as a Date/Number. If they can't be cast, they will remain String's.

提交回复
热议问题