Fix invalid JSON [duplicate] - php

This question already has answers here:
How can I parse a JSON string in which objects are not comma separated?
(5 answers)
Closed 4 years ago.
I have a huge file that unfortunately contains invalid JSON.
It looks like list of arrays, not separated with a comma:
[{
"key": "value"
}]
[
[{
"key": "value",
"obj": {}
},
{}
]
]
[{
"key": "value",
"obj": {}
}]
The content inside every square brackets pair seems to be a valid JSON by itself.
The question is how to fix this JSON quickly with "search and replace"? (or any other method)
Tried many combinations including replacing "][" to "],[" and wrapping the whole file with one more square brackets pair making it array of arrays.
Every time it gives me invalid JSON.
Please help.

You can replace the closing brackets with '],' and wrap the entire string in brackets.
This snippet illustrates the method with the supplied sample data by applying the algorithm and then calling eval on the resulting string.
let jsonString = `[{
"key": "value"
}]
[
[{
"key": "value",
"obj": {}
},
{}
]
]
[{
"key": "value",
"obj": {}
}]`;
jsonString = jsonString.replace( /]/g, '],' );
jsonString = '[' + jsonString + ']';
myObject = eval( jsonString );
console.log( typeof myObject);
console.log( myObject.length );
console.log( myObject );

This is a dynamic php solution, but I would cringe to have to use this as a reliable source of data. This is a bandaid. Whatever code is producing this invalid json NEEDS to be fixed asap.
My regex pattern will seek all occurrences of ], zero or more spaces, then ] then it will add a comma after the ].
The entire string is wrapped in square brackets to make the json string valid.
The risk may or may not be obvious to all -- if any of the actual keys or values contain strings that qualify for replacement, then they will be damaged. This is why using regex on json is not recommended.
Code: (Demo)
$bad_json = '[{
"key": "value"
}]
[
[{
"key": "value",
"obj": {}
},
{}
]
]
[{
"key": "value",
"obj": {}
}]';
$valid_json = "[" . preg_replace("~]\K(?=\s*\[)~", ",", $bad_json) . "]";
var_export(json_decode($valid_json, true));
Output:
array (
0 =>
array (
0 =>
array (
'key' => 'value',
),
),
1 =>
array (
0 =>
array (
0 =>
array (
'key' => 'value',
'obj' =>
array (
),
),
1 =>
array (
),
),
),
2 =>
array (
0 =>
array (
'key' => 'value',
'obj' =>
array (
),
),
),
)

Related

json_encode treats a single element array as object [duplicate]

This question already has answers here:
How to add square braces around subarray data inside of a json encoded string?
(3 answers)
Closed 6 months ago.
this is the json i have to produce
{
"email": "example#example.com",
"campaign": {
"campaignId": "p86zQ"
},
"customFieldValues": [
{
"customFieldId": "y8jnp",
"value": ["18-29"]
}
]
}
if i use
$data = [
"email" => $_POST['mail'],
"campaign" => [
"campaignId" => "4JIXJ"
],
"customFieldValues" => [
"customFieldId" => "y8jnp",
"value" => ["18-29"]
]
];
and i do json_encode($data)
value is an object, but it should be an array with a single element. Somehow json_encode treats it as an object. Can i force it to treat it as an array with a single element ?
Thanks in Advance
Adrian
At the moment, you have a single array with 2 elements, instead of an array with a single element of a sub-array. In order to get the json in the first section, you need to add another array level.
$data = [
"email" => $_POST['mail'],
"campaign" => [
"campaignId" => "4JIXJ"
],
"customFieldValues" => [
[
"customFieldId" => "y8jnp",
"value" => ["18-29"]
]
]
];
That will give you this:
{
"email": null,
"campaign": {
"campaignId": "4JIXJ"
},
"customFieldValues": [
{
"customFieldId": "y8jnp",
"value": ["18-29"]
}
]
}
if there is one single element in the array the json_encode will treat is as an object and the key of the object is the index of the array
to treat it as an array you can use array_values(<your_array>)

how to encode an url to json using php

I want to throw an URL along with some text output as a json from my php webpage and for this I have used json_encode() function in php and the following is my php array that will be converted to json:
$output= array (
'payload' =>
array (
'google' =>
array (
'expectUserResponse' => true,
'richResponse' =>
array (
'items' =>
array (
0 =>
array (
'simpleResponse' =>
array (
'textToSpeech' => '<speak>some text... <audio src=\"https://example.com\"></audio></speak>',
'displayText' => 'some text...',
),
),
),
'suggestions' =>
array (
0 =>
array (
'title' => 'cancel',
),
),
),
),
),
);
echo json_encode($output);
and this php code produces the following json output:
{
"payload": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "<speak>some text... <audio src=\\\"https://example.com\\\"></audio></speak>",
"displayText": "some text..."
}
}
],
"suggestions": [
{
"title": "cancel"
}
]
}
}
}
}
But I need the the following json output:
{
"payload": {
"google": {
"expectUserResponse": true,
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "<speak>some text... <audio src=\"https://example.com\"></audio></speak>",
"displayText": "some text..."
}
}
],
"suggestions": [
{
"title": "cancel"
}
]
}
}
}
}
I did not understand how to throw the URL in the json as per my requirment.
If you don't want the escaped slashes, you can use
json_encode($response, JSON_UNESCAPED_SLASHES);
to tell PHP not to escape these slashes.
But if you are talking about the backslashes, they have to be escaped like that since PHP interprets them as escape characters. You can always manually remove them on your receiving end.
'<speak>some text... <audio src=\"https://example.com\"></audio></speak>',
The double quotes do not need to be escaped here. The backslashes are treated literally because the string is single quoted. A backslash can only escape a single quote or another backslash inside of single quoted strings. Any other following character results in a literal backslash.
Either '<speak>some text... <audio src="https://example.com"></audio></speak>' (no escaping) or
"<speak>some text... <audio src=\"https://example.com\"></audio></speak>" (double quotes) should give the output you want.

How to convert JSON string to PHP object or array creation *code* [duplicate]

This question already has answers here:
print an array as code
(4 answers)
Closed 4 years ago.
FIRSTLY: This is a totally different question - How to convert JSON string to array
MY QUESTION...
I have a valid JSON string assigned to a php variable, $json.
I know that I can run it into json_decode($json, true); to parse into a php array at runtime, however I want to go a step beyond and convert this into a reusable php array code string, which can be simply copied and pasted into a php script, like $array = 'php array code here'.
For those who will inevitably ask "why?", an example:
to copy an example JSON endpoint parameter from an API's docs, then quickly convert to php array string code to paste into a test script as a valid test parameter for making a POST request
I know that I can do this:
$json = '
[
{
"ID": "1",
"Name": "Test One"
},
{
"ID": "2",
"Name": "Test Two"
}
]';
echo '<pre>';
echo '$phpArray = ' . print_r(json_decode($json));
echo '</pre>';
exit;
Which gets you close...
$phpArray = Array
(
[0] => stdClass Object
(
[ID] => 1
[Name] => Test One
)
[1] => stdClass Object
(
[ID] => 2
[Name] => Test Two
)
)
But there is of course still some work to do... currently I would copy this into Sublime Text or some other similar text manipulation tool and just use find/replace or regex find/replace in some cases. But what I am looking for is a quicker, more elegant solution whereby I could literally copy+paste that JSON into some script (or anywhere!), and run it to get this:
$phpArray = [
0 => [
'ID' => 1,
'Name' => 'Test One',
],
1 => [
'ID' => 2,
'Name' => 'Test Two',
],
];
Has someone created a good tool to do this already somewhere? I couldn't find anything. I am open to ANY elegant solution and will happily upvote any answer that is an improvement on this rudimentary means of bridging from the JSON to a PHP object / array creation code. Thanks!
<?php
$json = '
[
{
"ID": "1",
"Name": "Test One"
},
{
"ID": "2",
"Name": "Test Two"
}
]';
echo '$output = '.var_export(json_decode($json, true), true).';';
Output:
$output = array (
0 =>
array (
'ID' => '1',
'Name' => 'Test One',
),
1 =>
array (
'ID' => '2',
'Name' => 'Test Two',
),
);

JSON & Array get data with PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 5 years ago.
I have a question about some JSON and PHP, see json below.
How can I get the number string?
{
”data”: [
{
”numbers”: [
{
”number”: "XXXX",
”type”: ””
}
]
}
]
}
Ive tried with the following but its not working:
$item['numbers'][0]->number;
Note, the $item array is ok. I just do not know what is wrong here.
EDIT:
I should point out that there was an json_decode before.
So the structure looks like this:
Array
(
[0] => Array
(
[number] => XXXX
[type] =>
)
)
print_r($item['numbers']);
This doesn't work: $item['numbers'][0]['number'];
Error: Undefined offset: 0 in
Thanks!
if you want to direct access then use this code
$items->data->numbers->number;
you can use php json_decode().it takes a JSON encoded string and converts it into a PHP variable.
<?php
$json_data = '{
"data": [
{
"numbers": [
{
"number": "11",
"Type": ""
}
]
}
]
}';
$array=json_decode($json_data,true);
echo "<pre>";
print_r($array);
echo $array["data"][0]["numbers"][0]["number"];
then output
Array
(
[data] => Array
(
[0] => Array
(
[numbers] => Array
(
[0] => Array
(
[number] => 11
[Type] =>
)
)
)
)
)
Number:11
To get the number try this :
$myJSON->data->numbers->number;
Hope this will help you out... You are trying to access which does not actually exists.
try this code snippet here
<?php
ini_set('display_errors', 1);
$month_options = '{
"data": [
{
"numbers": [
{
"number": "10",
"Type": ""
}
]
}
]
}';
$array=json_decode($month_options,true);
echo $array["data"][0]["numbers"][0]["number"];
Use the json_decode() function of PHP.
$array = json_decode('{
”data”: [
{
”numbers”: [
{
”number”: "",
”Type”: ””
}
]
}
]
}', true);
Then you could access it as $array["data"]["numbers"]["number"];

Create JSON in PHP with multiple levels

I need to create json with multiple levels via PHP.
{
"accident": {
"dateTime": "2015-08-08T16:12:08",
"desc": "string"
},
"calculationInput": {
"idBlockCodes": [
{
"code": 51,
"value": 1
}
],
"wageRates": {
"labourRate1": 10,
"labourRate2": 11,
"labourRate3": 22,
"labourRate4": 33,
"labourRateD": 44,
"paintRate": 55
}
},
"caseNumber": "F4Q",
"vehicle": {
"adminData": {
"firstRegDate": "2015-07-08",
"numberPlate": "MI214AF"
},
"identification": {
"vin": "VF7S6NFZF56215577"
},
"owner": {
"city": "Praha",
"country": "CZE",
"email": "mail#mail.com",
"name": "Fero Taraba",
"phone": "777111222",
"phone2": "999555333",
"postCode": "07101",
"street": "Kukureliho 18"
}
}
}
I actuyltry this and it's possible for me to create single level json, with other words:
$data = array (
"caseNumber" =>"F4Q"
);
and then just easy:
$data_json= json_encode($data);
But can someone explain me how can I do this second or even 3th level tree to convert to JSON?
I will really appriciate your help guys. Thanks
EDIT:
Most of the answers really lead me right way, only problem now is this part:
"idBlockCodes": [
{
"code": 51,
"value": 1
}
],
where there is [ ] which represent some list of blockCodes. Any idea what to do with this ? :)
What is your question exactly?
You can create a array and then just encoding it to json?
$data = array(
'Key 1' => array(
'Key 2 - Key 1' => array(
'Key 3 - Key 1' => array()
)
)
);
echo json_encode($data);
Just use associative arrays
$data = array (
"caseNumber" =>"F4Q",
"vehicle" => array (
"adminData"=>
array(
"firstRegDate"=> "2015-07-08",
"numberPlate"=> "MI214AF"
),
"identification" =>
array(
"vin"=> "VF7S6NFZF56215577"
)
)
);
print out
{"caseNumber":"F4Q","vehicle":{"adminData":{"firstRegDate":"2015-07-08","numberPlate":"MI214AF"},"identification":{"vin":"VF7S6NFZF56215577"}}}
Use associative Arrays:
$data = array (
"caseNumber" =>"F4Q",
"vehicle" => array (
"adminData"=>
array(
"firstRegDate"=> "2015-07-08",
"numberPlate"=> "MI214AF"
),
"identification" =>
array(
"vin"=> "VF7S6NFZF56215577"
)
)
);
echo json_encode($data)
you get your brackets by putting an additional array around your object.
$data = array("idBlockCodes" => array(
array(
"code" => 51,
"value" => 1
)
)
);
print json_encode($data);
For you to convert all of your data to array:
You must first use json_encode();
$a = json_encode($yourData);
And then decode it:
$b = json_decode($a, true);
echo '<pre>';
print_r($b); //print it
It displays associated arrays with it

Categories