PHP: Json encode addslashes only to a specific value - php

I have a PHP array as follows:
Array
(
[Caller] => EFLwebsite
[CaseDetails] => Array
(
[Description] => This is a Site Readiness case.
[SAPCustomerCode] => 1001140090
[ProductNumber] => GWPDREVIV00000
[CustomerAssetSerialNumber] => 000000000418005207
[RequestedDate] => 2021/01/06
[RequestedTime] => 10:00:45
[BP] => CRM Test User
)
)
I need to convert the above array into json as follows:
{
"Caller":"EFLwebsite",
"CaseDetails":"{\"Description\":\"This is a Site Readiness case.\",\"SAPCustomerCode\":\"0100301500\",\"ProductNumber\":\"GWPDFCOND00000\",\"CustomerAssetSerialNumber\":\"000000000418005207\",\"RequestedDate\":\"2021\/01\/06\",\"RequestedTime\":\"23:54:12\",\"BP\":\"CRM Test User\"}"
}
I am using addslases() after json_encode but it returns as follows:
{
\"Caller\":\"EFLwebsite\",
\"CaseDetails\":{\"Description\":\"This is a Site Readiness case.\",\"SAPCustomerCode\":\"1001140090\",\"ProductNumber\":\"GWPDREVIV00000\",\"CustomerAssetSerialNumber\":\"000000000418005207\",\"RequestedDate\":\"2021\\/01\\/06\",\"RequestedTime\":\"10:00:45\",\"BP\":\"CRM Test User\"}
}
I need to add the slashes only to the second value which is CaseDetails
I also tried encoding the subarray separately and adding slashes as a string, but it is adding more slashes again.

I also have no idea why you would want to do this, but this should do the trick:
$array = [
"Caller" => "EFLwebsite",
"CaseDetails" => [
"Description" => "This is a Site Readiness case.",
"SAPCustomerCode" => "1001140090"
]
];
// first convert case details to json
$array["CaseDetails"] = json_encode($array["CaseDetails"]);
echo "<pre>";
print_r(json_encode($array)); // then convert everything to json
echo "</pre>";
This returns:
{"Caller":"EFLwebsite",
"CaseDetails":"{\"Description\":\"This is a Site Readiness case.\",\"SAPCustomerCode\":\"1001140090\"}"}

Using heredoc string with php. Docs
Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.
$case = addslases(json_encode($array['CaseDetails']));
$json = <<<EOT
{ "Caller": "{$array['Caller']}", "CaseDetails": {$case} }
EOT;
echo $json;

Related

Print result is different in the array function

I have a problem with the array PHP function, below is my first sample code:
$country = array(
"Holland" => "David",
"England" => "Holly"
);
print_r ($country);
This is the result Array ( [Holland] => David [England] => Holly )
I want to ask, is possible to make the array data become variables? For second example like below the sample code, I want to store the data in the variable $data the put inside the array.:
$data = '"Holland" => "David","England" => "Holly"';
$country = array($data);
print_r ($country);
But this result is shown me like this: Array ( [0] => "Holland" => "David","England" => "Holly" )
May I know these two conditions why the results are not the same? Actually, I want the two conditions can get the same results, which is Array ( [Holland] => David [England] => Holly ).
Hope someone can guide me on how to solve this problem. Thanks.
You can use the following Code.
<?php
$country = array(
"Holland" => "David",
"England" => "Holly"
);
foreach ($country as $index => $value)
{
$$index = $value;
}
?>
Now, Holland & England are two variables. You can use them using $Holland etc.
A syntax such as $$variable is called Variable Variable. Actually The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So there is this thing called
Destructuring
You can do it something like ["Holland" => $eolland, "England" => $england] = $country;
And now you have your array elements inside the variables.
Go read the article above if you want more information about this because it gets really useful (especially in unit tests usind data provders from my experience).
If you want to extract elements from an associative array such that the keys become variable names and values become the value of that variable you can use extract
extract($country);
To check what changed you can do
print_r(get_defined_vars());
Explanation on why the below does not work
$data = '"Holland" => "David","England" => "Holly"';
When you enclose the above in single quotes ' php would recognise it as a string. And php will parse a string as a string and not as an array.
Do note it is not enough to create a string with the same syntax as the code and expect php to parse it as code. The codes will work if you do this
$data = ["Holland" => "David","England" => "Holly"];
However, now $data itself is an array.
A simple copy of an array can be made by using
$data = $country;

Php how to add backslash inside array of strings

I have a below array:
Array
(
[0] => CLICK
[1] => CSC
)
After json_encode I got below one.
"["CLICK","CSC"]"
How to convert this into "[\"CLICK\",\"CSC\"]" this.
Any one help.
Some info was missing which I got after discussion.
They are manually replacing a lot of characters before returning json. Out of them they also include [ => "[ and ] => ]" due to their backend implications.
A simple json_encode was solution for this along with skipping those character replacement for specific this key.
Source:
<?php
$arr = [
"CLICK", "CSC"
];
echo json_encode(json_encode($arr)) . "\n";
Result:
"[\"CLICK\",\"CSC\"]"

Why is \r\n appearing when I JSON encode an array

I'm creating some arrays and turning them into JSON strings and I noticed something strange--some of the strings,
when I JSON encode them, are getting \r\n added onto the front and end of the of the strings.
The strings I'm encoding are pulled from HTML elements.
$arr = array(
'licStat' => $rows2[13]->nodeValue,
'expDate' => dateReplace($data[5]->nodeValue),
'dicAct' => $rows2[11]->nodeValue
);
echo json_encode($arr);
Expected output:
{"licStat":"Expired","expDate":"1999-12-20","dicAct":"Yes"}
Actual output:
{"licStat":"\r\n Expired\r\n ","expDate":"1999-12-20","dicAct":"\r\n Yes\r\n "}
It seems $rows2[13]->nodeValue and $rows2[11]->nodeValue have carry return and line feeds in them.
You can use trim() to get rid of them:
$arr = array(
'licStat' => trim($rows2[13]->nodeValue),
'expDate' => dateReplace($data[5]->nodeValue),
'dicAct' => trim($rows2[11]->nodeValue)
);
echo json_encode($arr);

How to correct an invalid JSON in php?

I have a problem.
For a mistake I have a lot of not valid JSON strings like this:
{
"d": {
"results": [
{
"__metadata": {
"uri": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=u0027non supporting iframesu0027&Market=u0027it-ITu0027&Adult=u0027Offu0027&Options=u0027DisableLocationDetectionu0027&WebSearchOptions=u0027DisableQueryAlterationsu0027&$skip=0&$top=1",
"type": "WebResult"
},
"ID": "7858fc9f-6bd5-4102-a835-0fa89e9f992a",
"Title": "something good",
"Description": "something "WRONG" here!",
"DisplayUrl": "www.devx.com/Java/Article/27685/1954",
"Url": "http://www.devx.com/Java/Article/27685/1954"
}
],
"__next": "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=u0027non%20supporting%20iframesu0027&Market=u0027it-ITu0027&Adult=u0027Offu0027&Options=u0027DisableLocationDetectionu0027&WebSearchOptions=u0027DisableQueryAlterationsu0027&$skip=50"
}
}
As you can see the field Description contains a bad string (" into "), so I'm not able to parse the json using php's json_decode, infact it returns NULL.
I've 1 million of wrong json, much more big than this (10 times).
How can I do in php?
In your case you could exploit the fact that strings in json could not be over a line. That is a snappy point to grab with s multi-line aware search and replace with a regular expression function like preg_match_callback in PHP.
/^\s+"[a-z_"]+": "([^"]*".*)",?$/mi
Whitespace at the beginning of the line; member-name in form of a valid name (only characters and underscore here) as a string; the : and then the broken string until the end of the line optionally followed by a comma ,?.
This regex already matches only invalid lines. However if your json also contains a valid string with \" inside, this regex does not really work.
So it's also good to place some checks that the replacement would do what it is intended.
$like = '... json-like but broken json string as in question ...';
// Fixing #1: member strings containing double-quotes on the same line.
$fix1Pattern = '/^(\s+"[a-z_]+": ")([^"]*".*)(",?)$/mi';
$fix1Callback = function ($matches) {
list($full, $prefix, $string, $postfix) = $matches;
$fixed = strtr($string, ['"' => '\"']);
if (!is_string(json_decode("\"$fixed\""))) {
throw new Exception('Fix #1 did not work as intended');
}
return "$prefix$fixed$postfix";
};
// apply fix1 onto the string
$buffer = preg_replace_callback($fix1Pattern, $fix1Callback, $like);
// test if it finally works
print_r(json_decode($buffer));
Keep in mind that this is limited. You might need to learn about regular expressions first which is a world of it's own. But the principle is often very similar: You search the string for the patterns that are the broken parts and then you do some string manipulation to fix these.
If the json string is much more broken, then this needs even more love, probably not to be easily solved with a regular expression alone.
Exemplary output for the code-example and the data provided:
stdClass Object
(
[d] => stdClass Object
(
[results] => Array
(
[0] => stdClass Object
(
[__metadata] => stdClass Object
(
[uri] => https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=u0027non supporting iframesu0027&Market=u0027it-ITu0027&Adult=u0027Offu0027&Options=u0027DisableLocationDetectionu0027&WebSearchOptions=u0027DisableQueryAlterationsu0027&$skip=0&$top=1
[type] => WebResult
)
[ID] => 7858fc9f-6bd5-4102-a835-0fa89e9f992a
[Title] => something good
[Description] => something "WRONG" here!
[DisplayUrl] => www.devx.com/Java/Article/27685/1954
[Url] => http://www.devx.com/Java/Article/27685/1954
)
)
[__next] => https://api.datamarket.azure.com/Data.ashx/Bing/Search/Web?Query=u0027non%20supporting%20iframesu0027&Market=u0027it-ITu0027&Adult=u0027Offu0027&Options=u0027DisableLocationDetectionu0027&WebSearchOptions=u0027DisableQueryAlterationsu0027&$skip=50
)
)

php json decode - get a value

I'm trying to extract a specific value from json content . Here it is link with the json code http://www.ebayclassifieds.com/m/AreaSearch?jsoncallback=json&lat=41.1131514&lng=-74.0437521 As you may see the the code displayed is
json({items:[{url:"http://fairfield.ebayclassifieds.com/",name:"Fairfield"},{url:"http://newyork.ebayclassifieds.com/",name:"New York City"}],error:null});
I need to extract the first url which in this case is "http://fairfield.ebayclassifieds.com/" and its name value which is "Fairfield" , I could do it with regex but I would prefer to use json_decode. Unfortunately when I try to decode it doesn't work
$json = getContent("http://www.ebayclassifieds.com/m/AreaSearch?jsoncallback=json&lat=41.1131514&lng=-74.0437521");
$test = json_decode($json, true);
As danp already said, the returned JSON is enclosed in a function call (specified by jsoncallback=json). You cannot get rid of this totally but, just using AreaSearch?jsoncallback=&lat=41.1131514&lng=-74.0437521 removes at least the json at the beginning of the string and you can get rid of the brackets by:
$json = trim(trim($json), "();");
with gives:
{items:[{url:"http://fairfield.ebayclassifieds.com/",name:"Fairfield"},{url:"http://newyork.ebayclassifieds.com/",name:"New York City"}],error:null}
Unfortunately, the JSON string is not valid. The keys (items, url, ...) have to be enclosed in quotes ". You can easily check that you get a syntax error with json_last_error() (error code 4, JSON_ERROR_SYNTAX).
Update:
According to this question: Invalid JSON parsing using PHP , you can make the JSON string valid with:
$json = preg_replace('/(\w+):/i', '"\1":', $json);
This encloses the keys in quotes.
If the string would be valid, then you could generate an array via:
$a = json_decode($json, true);
which would give you:
Array
(
[items] => Array
(
[0] => Array
(
[url] => http://fairfield.ebayclassifieds.com/
[name] => Fairfield
)
[1] => Array
(
[url] => http://newyork.ebayclassifieds.com/
[name] => New York City
)
)
[error] =>
)
So you could get the first URL and name via $a['items'][0]['url'] and $a['items'][0]['name'] resp.
But I repeat, the JSON you get as response is not valid and you cannot parse it with json_decode() in its original form.
Its not valid JSON. The keys should be wrapped inside quotes.
You can validate your json using the excellent JSON Lint site.
This is a valid version of the data returned:
{
"items": [
{
"url": "http://fairfield.ebayclassifieds.com/",
"name": "Fairfield"
},
{
"url": "http://newyork.ebayclassifieds.com/",
"name": "New York City"
}
],
"error": "null"
}

Categories