I need to convert a JSON string in array using PHP, but I need to escape double quotes.
$string = '["label":"Name","type":"text","placeholder":"Mario","name":"name",*],
["label":"Email","type":"email","placeholder":"mail#example.com","name":"email",*],
["label":"Message","type":"textarea","value":"In this box you can insert a link"]';
$jsonify = strip_tags($string,"<a>");
$jsonify = str_replace('*','"required":"required"',$jsonify);
$jsonify = str_replace('[','{',str_replace(']','}',$jsonify));
$jsonify = str_replace(array("\r\n", "\r"),"",$jsonify);
$jsonify = preg_replace("/\s+/", " ", $jsonify);
$jsonify = '['.jsonify.']';
echo $jsonify;
// OUTPUT IS:
[{"label":"Name","type":"text","placeholder":"Mario","name":"name","required":"required"}, {"label":"Email","type":"email","placeholder":"mail#example.com","name":"email","required":"required"}, {"label":"Message","type":"textarea","value":"In this box you can insert a link"}]
// BUT IS NOT JSON VALID. IT SHOULD BE THIS:
[{"label":"Name","type":"text","placeholder":"Mario","name":"name","required":"required"}, {"label":"Email","type":"email","placeholder":"mail#example.com","name":"email","required":"required"}, {"label":"Message","type":"textarea","value":"In this box you can insert a link"}]
How can I obtain a valid JSON string?
your string is not a json valid
this is a $string json valid
[
{
"label": "Name",
"type": "text",
"placeholder": "Mario",
"name": "name"
},
{
"label": "Email",
"type": "email",
"placeholder": "mail#example.com",
"name": "email"
},
{
"label": "Message",
"type": "textarea",
"value": "In this box you can insert a <a href='#' target='_blank'>link</a>"
}
]
test this,and remove other code strip_tags,Str_replace,preg_replace
echo json_encode($string);
You get a valid json file by simply passing your array/string to json_encode like this :
$array = array(
array("label" => "Name", "type" => "text", "placeholder" => "Mario", "name" => "name"),
array("label" => "Email", "type" => "email", "placeholder" => "mail#example.com", "name" => "email"),
array("label" => "Message", "type" => "textarea", "value" => "In this box you can insert a <a href='#' target='_blank'>link</a>")
);
$json = json_encode($array);
var_dump($json);
Related
This question already has answers here:
Creating a jSON object using php loop
(2 answers)
Create a Json array in a for loop - php
(2 answers)
Closed 1 year ago.
How to add commas to a json print?
$result = curl($url);
$result = json_decode($result , true);
$resultdata = $result ['data'];
foreach($resultdata as $data){
$print= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
print json_encode($print);
}
this is the response from my code
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
}
{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
}
{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
I want to have a comma for each json result
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
},{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
},{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
What you actually need to do is produce an array of results, which you can do by pushing values into an array in the loop, and then json_encode the array after the loop:
$print = array();
foreach($resultdata as $data){
$print[]= array(
"id" => $data['id'],
"username" => $data['username'],
"text" => $data['text']
);
}
print json_encode($print);
I don't get the point of having ',' but I'm guessing you want a valid json output. If so I guess that your result data is an array:
<?php
$result = [ 'data' => [
[
"id" => "17996292388215089",
"username" => "hanikfadhilah",
"text" => "Loh kapan ini huuu pengen"
],
[
"id" => "17877856039348099",
"username" => "titan_kdk",
"text" => "Mntb"
],
[
"id" => "17860767967398064",
"username" => "explorecentraljava",
"text" => "Terbaik fotonya lur"
]
]
];
so all what you need to do in order to get it as a valid json is:
print json_encode($result['data'], JSON_PRETTY_PRINT);
that produces output:
[
{
"id": "17996292388215089",
"username": "hanikfadhilah",
"text": "Loh kapan ini huuu pengen"
},
{
"id": "17877856039348099",
"username": "titan_kdk",
"text": "Mntb"
},
{
"id": "17860767967398064",
"username": "explorecentraljava",
"text": "Terbaik fotonya lur"
}
]
no need for any foreach loop.
json_encode()
How i can use a variable ($_REQUEST('subject')) inside simple quotation marks.
This is my code:
<?php
$uri = 'https://mandrillapp.com/api/1.0/messages/send.json';
$postString = '{//i can't quit this quotation mark
"key": "myapi",
"message": {
"html": "this is the emails html content",
"subject": "$_REQUEST['subject'];",//this dont work
"from_email": "email#mydomain.com",
"from_name": "John",
"to": [
{
"email": "test#hotmail.com",
"name": "Bob"
}
],
"headers": {
},
"auto_text": true
},
"async": false
}';
?>
That's JSON! Use json_encode and json_decode!
$json = json_decode ($postString, true); // true for the second parameter forces associative arrays
$json['message']['subject'] = json_encode ($_REQUEST);
$postString = json_encode ($json);
Although, it looks like you could save a step and yourself some trouble if you just build $postString as a regular php array.
$postArr = array (
"key" => "myapi",
"message" => array (
"html" => "this is the emails html content",
"subject" => $_REQUEST['subject'],
"from_email" => "email#mydomain.com",
"from_name" => "John",
"to" => array (
array (
"email" => "test#hotmail.com",
"name" => "Bob"
)
),
"headers" => array (),
"auto_text" => true
),
"async" => false
);
$postString = json_encode ($postArr);
change "subject": "$_REQUEST['subject'];" to "subject": "' . $_REQUEST['subject'] . '"
Try this:
$postString = '{
"key": "myapi",
"message": {
"html": "this is the emails html content",
"subject": "'.$_REQUEST['subject'].'", // Modify this way
"from_email": "email#mydomain.com",
"from_name": "John",
....
.....
}';
I have a json that is mapped on an object. The json looks like above:
{
"employeeId": "1",
"firstName": "John",
"lastName": "Doe",
"departments": [
{
"fieldName": "department",
"fieldValue": "[dep1, dep2]"
}
]
}
I need to take data from "fieldValue" and put it into an array.
json_decode doesn't work for me since the values inside are not quoted. It would be very helpful if I had it like "fieldValue": "[\"dep1\",\"dep2\"]", but I cannot control how I receive it. Does somebody has some suggestions on how to make an array out of a string that looks like that?
Not sure that it is good variant, but you can use json_decode function two time:
$json = '{
"employeeId": "1",
"firstName": "John",
"lastName": "Doe",
"departments": [
{
"fieldName": "department",
"fieldValue": "[dep1, dep2]"
}
]
}';
$decodedJson = json_decode($json);
$fieldValue = json_decode(strtr($decodedJson->departments[0]->fieldValue, array(
'[' => '["',
']' => '"]',
',' => '","'
)));
var_dump($fieldValue);
$var = "[dev1, dev2]";
$keywords = preg_split('/[\[+\]]/', $var);
$keywords[1] will be your answer.
Then, you can split the $keywords[1] variable into an array using str_split()
So I'm trying to send a dynamic email with PHP. Now here's what I have
$postString = '{
"key": "xxx",
"message": {
"html": "this is the emails html content",
"text": "this is the emails text content",
"subject": "this is the subject",
"from_email": "email#email.com",
"from_name": "Joe",
"to": [
{
"email": "Joe# Joe",
"name": "Joe# Joe"
}
],
"attachments": [
]
},
"async": false
}';
Now I want "html" to be a variable. So I did this
"html": $var,
Sadly that doesn't work. Not does {} or using single quotes. Any ideas? It gets picked up as a string, by the way.
Variables are not interpolated in strings delimited by single quotes. There are a few ways around this. The following example uses concatenation.
$postString = '{
"key": "xxx",
"html": "' . $var . '",
"message": {
"html": "this is the emails html content",
"text": "this is the emails text content",
"subject": "this is the subject",
"from_email": "email#email.com",
"from_name": "Joe",
"to": [
{
"email": "Joe# Joe",
"name": "Joe# Joe"
}
],
"attachments": [
]
},
"async": false
}';
To be honest with you, this would be a lot easier if you just used an array and then encoded it into JSON using json_encode().
As mentioned in my comment, this would work a lot better
$post = [
'key' => 'xxx',
'message' => [
'html' => $var,
'text' => 'this is the emails text content',
'subject' => 'this is the subject',
'from_email' => 'email#email.com',
'to' => [
['email' => 'Joe# Joe', 'name' => 'Joe# Joe']
],
'attachments' => []
],
'async' => false
];
$postString = json_encode($post);
Obligatory legacy PHP note: If you're stuck on a PHP version lower than 5.4, you obviously can't use the shorthand array notation. Substitute [] with array() if that's the case.
I've got a request to present the data in the following format as a JSON feed:
{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
However in my PHP code, I think I need to have a key itterator - but I end up with this format:
{
"0": {
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
"1": {
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
}
Any ideas on how to build the first data set with out having the index iterator?
simple create an array of objects, no need for the key (notice the [ ] surrounding your list)
json.txt
[{
"id": "123",
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "456",
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}]
example.php
<?php
$data = json_decode(file_get_contents('./json.txt'));
?>
It can be built like this:
$arr = array(
array(
'id' => 123,
'info' => array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL'
)
),
array(
'id' => 456,
'info' => array(
'code' => 'ZDN',
'description' => 'test2',
'type' => 'CLR'
)
)
);
echo json_encode($arr);
Outputs
[
{
"id": 123,
"info": {
"code": "ZGE",
"description": "test1",
"type": "AVL"
}
},
{
"id": 456,
"info": {
"code": "ZDN",
"description": "test2",
"type": "CLR"
}
}
]
the JSON format you've specified in the first example (ie the requested format) is not valid JSON.
A valid JSON string must evaluate to a single Javascript object; the example you've given evaluates to two Javascript objects, separated by a comma. In order to make it valid, you would need to either enclose the whole thing in square brackets, to turn it into a JS array or enclose it in curly braces, and give each of the two objects a key.
The PHP code you've written is doing the second of these two options. It is therefore generating valid JSON code, about as close to the original request as could be expected while still being valid.
It would help if you'd shown us the PHP code that you've used to do this; without that, I can't really give you advice on how to improve it, but if you want to switch to the square bracket notation, all you need is to put your PHP objects into an unkeyed array, and json_encode() should do it all for you; you shouldn't need to use a keyed array or an iterator for that.
The only reason json_encode should produce the output you're seeing is adding another named key to the array that you're passing to json_encode, by default it should work as you want:
$json = '[
{
"id": "123",
"recall_info": {
"code":"ZGE",
"description": "test1",
"type": "AVL",
"date": "09/08/2012"
}
},
{
"id": "123",
"recall_info": {
"code": "ZDN",
"description": "test2",
"type": "CLR",
"date": "16/02/2012"
}
}
]';
$php = array(
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test1',
'type' => 'AVL',
'date' => '09/08/2012'
)
),
(object) array(
'id' => '123',
'recall_info' => (object) array(
'code' => 'ZGE',
'description' => 'test2',
'type' => 'CLR',
'date' => '16/02/2012'
)
)
);
var_dump(json_encode($php));