json multi array syntax - php

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

Related

Convert PHP to JSON with Nested Array

I have a PHP variable I need to convert to JSON string.
I have following PHP code:
$username="admin";
$password="p4ssword";
$name="Administrator";
$email="myname#smsfree4all.com"
$params=compact('username', 'password','name','email', 'groups');
json_encode($params);
This works fine. But what I am not sure about is how do I encode the properties in PHP with nested key value pairs shown below:
{
"username": "admin",
"password": "p4ssword",
"name": "Administrator",
"email": "admin#example.com",
"properties": {
"property": [
{
"#key": "console.rows_per_page",
"#value": "user-summary=8"
},
{
"#key": "console.order",
"#value": "session-summary=1"
}
]
}
}
What is this with # before key value?
Something like this should do it
$username="admin"; //more variables
$params=compact('username' /* more variables to be compacted here*/);
$params["properties"] = [
"property" => [
[
"#key" => "console.rows_per_page",
"#value"=> "user-summary=8"
],
[
"#key"=> "console.order",
"#value"=> "session-summary=1"
]
]
];
echo json_encode($params);
The manual has more examples you can use
Notice that:
A key~value array is encoded into an object
A regular array (array of arrays here) is encoded into an array
Those are all the rules you need to consider to encode any arbitrary object
Something like this perhaps?
$properties = [
'property' => [
['#key' => 'console.rows_per_page', '#value' => 'user-summary=8'],
['#key' => 'console.order', '#value' => 'session-summary=1']
]
];
It's difficult to tell what you're asking.
You can nest in PHP using simple arrays, very similar to JavaScript objects:
$grandparent = array(
"person1" => array(
"name" => "Jeff",
"children" => array(
array("name" => "Matt"),
array("name" => "Bob")
)
),
"person2" => array(
"name" => "Dillan",
"children" => array()
)
);

PHP - How to create JSON with JSON object inside [duplicate]

This question already has answers here:
create nested JSON object in php?
(7 answers)
Closed last year.
I have to comunicate with some API which expect JSON.
Until now I was fine because I needed just simple json so I just create array like this:
$data = array (
"firstName" => "TEXT1",
"lastName" => "TEXT2",
"license" => "TEXT3",
"password" => "TEXT4",
"username" => "TEXT5"
);
And after that just simple
$data_string = json_encode($data);
So final JSON looks like:
{
"firstName": "TEXT1",
"lastName": "TEXT2",
"license": "TEXT3",
"password": "TEXT4",
"username": "TEXT5"
}
However now I have to change it a bit and I am confuse, my new JSON shoud looks like:
{
"contact": {
"city": "New Yourk",
"email": "my#mail.com",
"phone": "777888999",
"postCode": "07101",
"street": "Street N. 12"
},
"enabled": true,
"firstName": "Robert",
"lastName": "Exer",
"username": "login#login.com",
"license": "text",
"password": "text"
}
As you can see it is basicly just added contact part. I was thinking how I can do this but only think I found was something like to insert array to existing $data array and then json_encode this but this will not give me a contract: at start.
Of course there is possible to do it some other way like create one json and then another and hardly connect string and so on. But i believe there have to be some better way how to do things like this.
I apprciate any advise:)
Just put an array in the value of contact:
$data = array(
'contact' => array(
'city' => 'New York',
'email' => 'my#mail.com',
//...
),
'enabled' => true,
'firstName' => 'Robert',
'lastName' => 'Exer',
//...
);
$data_string = json_encode($data);
An array can contain another array, which will be encoded as a separate object inside the previous object:
$data = array (
"contact" => array(
"city" => "New Yourk",
"email" => "my#mail.com",
"phone" => "777888999",
"postCode" => "07101",
"street" => "Street N. 12"
),
"enabled": true,
.. etc
);

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

Edit a Json File

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.

regex wrap strings in quotes

I have an array like the example below but much much bigger (4000 lines long):
array(
"id" => array(
"a" => "",
"b" => "",
"c" => Needs Quotes Around Me
), "id" => array(
"a" => "",
"b" => "",
"c" => Needs Quotes Around Me
"d" => Needs Quotes Around Me
)
);
The string values for some reason dont have the quotes ("") around them and the colon seperator. Some of the strings are numbers but can be treated as a string and some have spaces and the # symbols as some are email addresses but I need to wrap all of them in "STRING HERE",
Im trying to use reg_replace with something like this =>\s([a-zA-Z0-9\#\s])+$ but it doesnt replace the matched string with the string it found? Ive done quite a bit of googling but cant seem to get it right, please tell me where Im going wrong.
What I end up with is:
array(
"id" => array(
"a" => "",
"b" => "",
"c" => "[a-zA-Z0-9\#\s]",
), "id" => array(
"a" => "",
"b" => "",
"c" => "[a-zA-Z0-9\#\s]",
"d" => "[a-zA-Z0-9\#\s]",
)
);
This perl script works for the example given
perl -pe 's/(?<==> )(?!"|array\()(.*)/"$1",/' EXAMPLEFILE.txt
the following output is produced:
array(
"id" => array(
"a" => "",
"b" => "",
"c" => "Needs Quotes Around Me",
), "id" => array(
"a" => "",
"b" => "",
"c" => "Needs Quotes Around Me",
"d" => "Needs Quotes Around Me",
)
);
It required placing circular brackets around the regex. As simple as this sounds its only easy when you know how.

Categories