I am trying to create a JSON representation of data stored in mySQL.
I am trying to document a RESTful API.
I am using PHP's json_encode() function.
I have a table that contains data such as
1) name 2) parent 3) data_type (object/array/string/number to match JSON data types) 4) value
I am trying to create a generalized function that will allow me to build these JSON strings by simply adding data to the mySQL database.
I am having problems with working with both objects and arrays though.
For instance the JSON should be:
{
"sessionToken":"","roleName":""
,"data":[
{
"methodTypes":[""] , "objects":[""]
}
]
}
however it is coming out as:
{
"sessionToken":"","roleName":""
,"data":[
{
"methodTypes":[""]
}
,{
"objects":[""]
}
]
}
this is indicating to me for some reason my code is adding an object for both methodType and objects, where as it should just be within the single object.
I am trying to first create an array containing methodTypes and objects. Then I create an object in the format of $objects->$A, and I make this equal the array created in the first step. Then I add in to the primary data array for the JSON generation.
I have been searching for examples that show usage examples of JSON when both arrays and objects are required in the same JSON without success.
Any pointers in the correct direction would be greatly appreciated.
UPDATE #1:
var_dump of the array that is being fed to json_encode() is:
array(3) { ["sessionToken"]=> string(0) "" ["roleName"]=> string(0) "" ["data"]=> array(2) { [0]=> array(1) { ["methodTypes"]=> array(1) { [0]=> string(0) "" } } [1]=> array(1) { ["objects"]=> array(1) { [0]=> string(0) "" } } } }
where as if I take a known good JSON and do a json_decode() then the var_dump looks like:
object(stdClass)#3 (3) { ["sessionToken"]=> string(0) "" ["roleName"]=> string(0) "" ["data"]=> array(1) { [0]=> object(stdClass)#4 (2) { ["methodTypes"]=> array(1) { [0]=> string(0) "" } ["objects"]=> array(1) { [0]=> string(0) "" } } } }
or
array(3) { ["sessionToken"]=> string(0) "" ["roleName"]=> string(0) "" ["data"]=> array(1) { [0]=> array(2) { ["methodTypes"]=> array(1) { [0]=> string(0) "" } ["objects"]=> array(1) { [0]=> string(0) "" } } } }
if I set it to TRUE to return array instead of object.
var_dumpof the array you're using withjson_encode? I think you might have your data structured wrong on that endjson_encodewill adjust to javascript object if needed. For example$arr['foo']=array('bar', 'gggg')will convert to{"foo":["bar", "gggg"]}