Reputation: 55
Team,
I'm trying to generate a JSON string but I keep running into issues with (I guess) quotes.
Code:
<?php
// JSON data generated
$attachment = "[{
'contentType': 'application/json',
'content': {
'type': 'mytype',
'body': [{
'type': 'TextInfo',
'text': 'TEST TEXT',
'wrap': true
}]
}
}]";
// Add attachment string (JSON data) in an array
$mydata = array(
'space' => "abc",
'markdown' => "**welcome**",
'attachment' => $attachment
);
// Turn array into one big JSON string
$send_json = json_encode($data2);
What this should generate:
{
"space": "abc",
"markdown": "**welcome**",
"attachment": [{
'contentType': 'application/json',
'content': {
'type': 'mytype',
'body': [{
'type': 'TextInfo',
'text': 'TEST TEXT',
'wrap': true
}]
}
}]
}
It feels like I'm missing something (besides the required knowledge ;-).
Upvotes: 1
Views: 1108
Reputation: 48000
I don't understand how your $attachment
data could be "JSON data generated" because it is invalid json ...I hope you aren't manually crafting that json string. You should always just generate an array/object and then call json_encode()
when you are finished populating the iterable variable with data.
I have repaired your invalid $attachment
string by replacing the "
with '
and vice versa.
To nest this data inside $mydata['attachment']
you will need to decode the json first.
Finally, once your array data is completely built, THEN you call json_encode()
on $mydata
. The PRETTY_PRINT flag is just to aid readability in this post.
Code: (Demo)
$attachment = '[{
"contentType": "application/json",
"content": {
"type": "mytype",
"body": [{
"type": "TextInfo",
"text": "TEST TEXT",
"wrap": true
}]
}
}]';
$mydata = array(
'space' => "abc",
'markdown' => "**welcome**",
'attachment' => json_decode($attachment)
);
$send_json = json_encode($mydata, JSON_PRETTY_PRINT);
echo $send_json;
Output:
{
"space": "abc",
"markdown": "**welcome**",
"attachment": [
{
"contentType": "application\/json",
"content": {
"type": "mytype",
"body": [
{
"type": "TextInfo",
"text": "TEST TEXT",
"wrap": true
}
]
}
}
]
}
Upvotes: 1