Edit a Json File - php

I am trying to use a jQuery gantt as a wordpress plugin. Currently I'm stuck on editing the data.json. I use a php form to populate a new item. When submitting the form, it will add data to the file, but behind the closing square brackets.
[{
...
},
{ "name" : "Vermessung"
, "desc" : ""
, "values": [
{ "id" : "5"
, "from" : "/Date(1363132800000)/"
, "to" : "/Date(1368655200000)/"
, "desc" : "Vom Beauftragen der Vermessung bis zur tatsächlichen Vermessung"
, "customClass": "ganttBlue"
, "label" : "Vermessung"
}
]
}
]
After submitting the form it looks like this:
[{
...
},
{ "name" : "Vermessung"
, "desc" : ""
, "values": [
{ "id" : "5"
, "from" : "/Date(1363132800000)/"
, "to" : "/Date(1368655200000)/"
, "desc" : "Vom Beauftragen der Vermessung bis zur tatsächlichen Vermessung"
, "customClass": "ganttBlue"
, "label" : "Vermessung"
}
]
}
]{"name":null,"desc":null,"values":{"id":null,"from":null,"to":null,"desc":null,"customClass":null,"label":null}}
This is the requested php Code which will adding stuff to the json:
$file = jQg_BASENAME_DIR.'/inc/data.json';
log_me('This is a message for debugging purposes');
if(isset($_POST['submit'])){
$json = file_get_contents( $file );
$data = json_decode($json);
// convert form data to json format
$postArray = array(
"name" => $_POST['name'],
"desc" => $_POST['desc'],
"values" => array(
"id" => $_POST["value_id"],
"from" => $_POST['value_from'],
"to" => $_POST['value_to'],
"desc" => $_POST['value_desc'],
"customClass" => $_POST['value_class'],
"label" => $_POST['value_label']
)
); //you might need to process any other post fields you have..
$json = json_encode( $postArray );
array_push($json, $postArray);
// write to file
file_put_contents( $file, $json, FILE_APPEND);
I also can't establish the square bracket after value. How can I fix this?

As I said in my comment
$json = file_get_contents( $file );
// $json is now a string
$data = json_decode($json);
// $data is a PHP object
// So lets call the second array $data->someArray
// since I do not know what it is called looking at your file
// convert form data to PHP array format
$postArray = array(
"name" => $_POST['name'],
"desc" => $_POST['desc'],
"values" => array(
"id" => $_POST["value_id"],
"from" => $_POST['value_from'],
"to" => $_POST['value_to'],
"desc" => $_POST['value_desc'],
"customClass" => $_POST['value_class'],
"label" => $_POST['value_label']
)
); //you might need to process any other post fields you have..
// $postArray is a PHP object
// $json = json_encode( $postArray ); // do NOT convert here
array_push($data->someArray, $postArray);
$json = json_encode($data);
// write to file
file_put_contents( $file, $json, FILE_APPEND);

Your values field is an array of objects instead of an object (the encoding of a php associative array is a json oject). So for values to have square brackets instead of "values" => array() you would need "values" => array( array("id" => ... etc. ) )
As for your first problem you've inverted the json_encoding. First push your postArray into data, then json_encode data.

Related

Parse JSON with PHP: Syntax complication

I'm getting the following errors:
Notice: Undefined index: value in C:\fileSystemLocation/phpFile.php on line 43
Notice: Undefined index: value in C:\fileSystemLocation/phpFile.php on line 44
when I'm trying to parse the following json data:
"data":[
"phone":[
{"value":"",
"primary":true
}],
"email":[
{"value":"",
"primary":true
}]
]
With the following statements
$response = json_decode($json_response, 1);
// Gets the count of records returned from the api. Used in the for loop to go through response 1 array element at a time.
$count = Count($response['data']);
//create array of the json data we want to export to csv
for ($x=0; $x<$count; $x++)
{
$jsonDataInArray[] = array
(
"phone" => $response['data'][$x]['phone']['value'],
"email" => $response['data'][$x]['email']['value'],
)
}
What is wrong with the syntax of the above 2 statements? I'm wondering if there is any error with my syntax above specifically with "phone" => $response['data'][$x]['phone']['value'],
"email" => $response['data'][$x]['email']['value'],
Looks like your JSON data is missing {} (malformed) and, also, you're using a phone key (alphabetical) on a numerical key array ([]). To use alphabetical keys you have to have a dictionary ({}, key-value arrays). Looks like your JSON should be like this:
{
"data" :
[
{
"phone" :
{
"value" : "",
"primary" : true
},
"email" :
{
"value" : "",
"primary" : true
}
}
]
}
Also remember that the function to count items in an array is count(), not Count() (capitalization matters).
I would do this then:
$jsonDataInArray = array();
$response = json_decode( $json_response, TRUE );
$data = $response['data'];
$count = count( $data );
foreach ( $data AS $index => $object )
{
$values = array(
"phone" => $data[$index]['phone']['value'],
"email" => $data[$index]['email']['value']
);
array_push( $jsonDataInArray, $values );
}
Here's the syntax that worked for me:
"phone" => $response['data'][$x]['phone'][0]['value'],
"email" => $response['data'][$x]['email'][0]['value']
The ending objects in the json data looked like (WARNING: not the whole string of json data, just the end):
"phone":[{"value":"","primary":true}],"email":[{"value":"","primary":true}]
and since there are arrays, I have to include the [0]
The following code:
"phone" => $response['data'][$x]['phone']['value'],
"email" => $response['data'][$x]['email']['value']
Would work with these ending json data objects (WARNING: not the whole string of json data, just the end):
"phone":{"value":"","primary":true},"email":{"value":"","primary":true}
Your syntax inside your loop is wrong. Change:
"email" => $response['data'][$x]['email']['value'],
To:
$email = $response['data'][$x]['email']['value'];

json multi array syntax

I create array for json this's multiple array condition with syntax :
$row_set = array(
"err" => "",
"msg" => "",
"data" => array(
"f" => "",
"hotel"=> array(
"att" => "",
"name" => "name",
"city" => "",
"country" => ""
),
"city" => array(
"att" => "",
"name" => "",
"region" => "",
"country" => "",
"nr_hotels" => ""
)
)
);
echo json_encode($row_set);
But when I test it in jsonlint.com there is an error :
Parse error on line 1:
array("err"=>"","ms
^
Expecting '{', '['
Please help me. Where is the error from my syntax?
Your code generates:
{"err":"","msg":"","data":{"f":"","hotel":{"att":"","name":"name","city":"\r\n","country":""},"city":{"att":"","name":"","region":"","country":"","nr_hotels":""}}}
which is perfectly valid JSON.
You are parsing PHP code, not JSON in validator.
Your code is run perfect on jsonlint
$row_set =array(
"err"=>"",
"msg"=>"",
"data"=>array(
"f"=>"",
"hotel"=>array(
"att"=>"",
"name"=>"name",
"city"=>"",
"country"=>""
),
"city"=>array(
"att"=>"",
"name"=>"",
"region"=>"",
"country"=>"",
"nr_hotels"=>""
)
));
echo json_encode($row_set);
Output
{"err":"","msg":"","data":{"f":"","hotel":{"att":"","name":"name","city":"","country":""},"city":{"att":"","name":"","region":"","country":"","nr_hotels":""}}}
You have to copy json_encode output on jsonlint and you tried to copy php array which is wrong.
Check Output

PHP & JSON: Inserting an array in a nested array

I am creating a JSON structure to be passed back to Ajax. I would like to insert 'para' => "Hello" into "content" like this:
{
"sections": {
"content": [{
"para": "Hello"
}]
}
}
I tried using this code:
$array = array('sections' => array());
array_push($array["sections"], array("content" => array())); // content must be initialized as empty
array_push($array["sections"][0], array("para" => "Hello"));
But I received this instead:
{
"sections": [{
"content": [],
"0": {
"para": "Hello"
}
}]
}
If I try array_push($array["sections"]["content"], array("para" => "Hello")), I get an error instead. How do I insert an array into "content"? What am I doing wrong?
If I understood your intentions correctly, here's the array structure you're aiming for:
array("sections" => array(
"content" => array("para" => "Hello"),
));
However, in Javascript [] represents an array and {} represents an object. If you're trying to create an object with a property of "0", that's not possible in PHP. Variable names have to start with a letter or underscore.
Here's an array of content objects:
$content = new stdClass();
$content->para = 'hello';
array("sections" => array(
"content" => array($content),
));
To add arrays of contents:
array("sections" => array(
"content" => array(
array("para" => "Hello"),
array("para" => "Hello"),
array("para" => "Hello"),
),
));
You can also construct your own contents array first if you're iterating over an index and then json_encode it. Basic example:
$content = array();
for (i=0; i <3; i++) {
$content[] = array('para' => 'hello');
}
json_encode(array("sections" => array(
"content" => array($content),
)));
To convert that to JSON, put your array inside a json_encode() call.
$array['sections'] = array("content" => array(array("para" => "Hello")));
echo json_encode($array);
will give the result in desired format

Defining multidimensional array while storing form data in JSON format in php

I have to convert form data to JSON format. I am trying to achieve this:-
{"appConfiguration" : {
"configuration_name" = "AS400 Configuration",
"configuration_version" = "1.001",
"connection" : [ {
"ip_address" : [ “10.10.10.01”,
“10.10.10.02”,
“10.10.10.03”
// all saved IP Address.
]
"port" : "23"
"ssl" : "NO",
"device_name" : "Agicent Device",
"name" : "Puga",
"user" : "smart gladiator",
"password" : "sgl2013",
"barcode_enter" : "NO",]}}
This is what my JSON should look like. I am able to store data in single-dimension array; how do I create a structure like this?
"connection":["ohiuh","ghu","ip_address":["something","something","something"]]
Try with this
$arr = array('connection'=>array("ohiuh","ghu" , json_encode(array("ip_address"=>array("something","something","something")))));
echo json_encode($arr);
To get for example ip_address you can do this:
$array = json_decode($jsonstring);
echo $array['connection']['ip_address']['something'];
This will decode your json string into an multidimensional array and than you can simply echo it.
To encode it:
$test = array("appConfiguration" => array("configuration_name"=> "AS400 Configuration", "configuration_version" => "1.001", "connection"=> array("ip_address" => array('10.10.10.01', '10.10.10.02', '10.10.10.03'), "port" => "23",
"ssl" => "NO",
"device_name" => "Agicent Device",
"name" => "Puga",
"user" => "smart gladiator",
"password" => "sgl2013",
"barcode_enter" => "NO")));
echo(json_encode($test));
To use data you get from a form you can do this:
$array = array('connection'=>array($_POST["ohiuh"],$_POST["ghu"] , array("ip_address"=>array($_POST["ip_adress1"],$_POST["ip_adress2"],$_POST["ip_adress3"])))));
echo json_encode($array);
Write a form with the value you need and than post them. Than create the array with the $_POST["something"] values and encode this array to json with json_encode();
Hope this is now the answer to your question.

Find substring in MongoDB array from another array from PHP

I have a more complex document "schema" saved in Mongo but the part that I need to match looks like this
"tags" : [
{
"tag" : "accompong maroon festival",
"type" : "label"
},
{
"tag" : "jamaica",
"type" : "label"
},
{
"tag" : "maroon warrior",
"type" : "label"
},
{
"tag" : "maroons",
"type" : "label"
},
{
"tag" : "caribbean culture",
"type" : "label"
},
{
"tag" : "rum",
"type" : "label"
}
}
I am using PHP to query the Mongo database and I have to query each document against an array of possible words.
array(
'boxing',
'warrior'
)
I don't know how to write the code in order to try to match the array that I have with the dataset saved in Mongo.
For now I only try to see if the tag is within the array of words
$data = $this->event_model->find_by(
array
(
'tags.tag' => array
(
'$in' => $Words
),
'published' => 'y'
)
);
I've resolved this problem by first creating an array that uses MongoRegex to search through the tags and by adding this array to the $or procedure
$or_array = array();
foreach($Words as $w)
{
$or_array[] = array(
'tags.tag' => new MongoRegex('/.*'. $w .'.*/i')
);
}
$data = $this->event_model->find_by(
array
(
'$or' => $or_array,
'published' => 'y'
)
);

Categories