Convert PHP string to JSON array(key:value) - php

I have the following string that I receive from an API call:
a = "{
"option1"=>"Color",
"attribute1"=>{0=>"Black", 1=>"White",2=>"Blue"},
"option2"=>"Size",
"attribute2"=>{0=>"S", 1=>"L",2=>"M"}
}"
I would like to convert it to a JSON array; So, I have tried JSON_encode(), but it returns the following string:
""{\"option1\"=>\"Color\",\"attribute1\"=>{0=>\"Black\", 1=>\"White\",2=>\"Blue\"},\"option2\"=>\"Size\",\"attribute2\"=>{0=>\"S\", 1=>\"L\",2=>\"M\"}}""
Could you please advise me on how to achieve what i want.
Thanks

The preferable way would be affecting the service which gives you such kind of strings to get a valid JSON string(if it's possible). At the moment, if it's about adapting some "arbitrary" string to JSON notation format and further getting a JSON "array" use the following approach with preg_replace and json_decode functions:
$json_str = '{
"option1"=>"Color",
"attribute1"=>{0=>"Black", 1=>"White",2=>"Blue"},
"option2"=>"Size",
"attribute2"=>{0=>"S", 1=>"L",2=>"M"}
}';
// To get a 'pure' array
$arr = json_decode(preg_replace(["/\"?(\w+)\"?=>/", "/[\r\n]|\s{2,}/"], ['"$1":', ''], $json_str), true);
print_r($arr);
The output:
Array
(
[option1] => Color
[attribute1] => Array
(
[0] => Black
[1] => White
[2] => Blue
)
[option2] => Size
[attribute2] => Array
(
[0] => S
[1] => L
[2] => M
)
)
To get a JSON string representing an array:
$json_arr = json_encode($arr);
print_r($json_arr);
The output:
{"option1":"Color","attribute1":["Black","White","Blue"],"option2":"Size","attribute2":["S","L","M"]}

Related

How would I got about parsing a php variable with this string stored in it?

I'm new to php and am trying to parse a string I'm getting. The string is the result of a bash script I'm running, and I'm storing the output into a php variable. Here is the output I'm getting:
1/1 [==============================] - 1s 1s/step
[
{
"image_id": "mahomes1",
"mean_score_prediction": 6.3682564571499825
},
{
"image_id": "mahomes2",
"mean_score_prediction": 6.7501190304756165
},
{
"image_id": "mahomes3",
"mean_score_prediction": 6.3136263862252235
},
]
How would I go about parsing this string so that I can create a dictionary that stores the "image_id" value with the "mean_score_prediction" value?
Your data is almost valid JSON, other than the beginning text and the comma between the final } and closing ]. By cleaning those issues up, you can then use json_decode on it to get a dictionary as an array of objects (or arrays, dependent on your preference):
$string = preg_replace(array('/^[^\v]+/', '/,(\s+\])/'), array('', '$1'), $string);
$dict = json_decode($string);
print_r($dict);
Output:
Array (
[0] => stdClass Object (
[image_id] => mahomes1
[mean_score_prediction] => 6.36825645715
)
[1] => stdClass Object (
[image_id] => mahomes2
[mean_score_prediction] => 6.7501190304756
)
[2] => stdClass Object (
[image_id] => mahomes3
[mean_score_prediction] => 6.3136263862252
)
)
To get an array of arrays, call json_decode with a second parameter of true i.e.
$dict = json_decode($string, true);
Demo on 3v4l.org

PHP insert keys in string

I have the following string:
{"1":"http://localhost:8888/classecar/uploads/dropzone/ferrari1.jpg","2":"http://localhost:8888/classecar/uploads/dropzone/ferrari2.jpg","3":"http://localhost:8888/classecar/uploads/dropzone/ferrari3.jpg","4":"http://localhost:8888/classecar/uploads/dropzone/ferrari4.jpg"}
How can I get rid of the numbers preceding "http..." and transform this same numbers in array keys?
Like this:
[0] => "http...",
[1] => "http...",
[2] => "http...",
That looks like a JSON string, so you could decode it.
You could try
$array = json_decode($string, true);
You may also need to reindex the array so it is 0 based; so something like
$array = array_values(json_decode($string, true));
you are having an array data in JSON formation. you have to use a PHP function json_decode to get an result.
$php_array = json_decode($your_array[0], true);
//to see your array
print_r($php_array);
You are missing something I think.
Look at this snippet:
$a=[
0 => '{
"1":"http:\/\/localhost:8888\/classecar\/uploads\/dropzone\/ferrari1.jpg",
"2":"http:\/\/localhost:8888\/classecar\/uploads\/dropzone\/ferrari2.jpg",
"3":"http:\/\/localhost:8888\/classecar\/uploads\/dropzone\/ferrari3.jpg",
"4":"http:\/\/localhost:8888\/classecar\/uploads\/dropzone\/ferrari4.jpg"
}'
];
echo "<pre>";
print_r(json_decode($a[0],TRUE));
it returns:
Array
(
[1] => http://localhost:8888/classecar/uploads/dropzone/ferrari1.jpg
[2] => http://localhost:8888/classecar/uploads/dropzone/ferrari2.jpg
[3] => http://localhost:8888/classecar/uploads/dropzone/ferrari3.jpg
[4] => http://localhost:8888/classecar/uploads/dropzone/ferrari4.jpg
)
This will work considering that the array value is a "string" containing a json object.
A var_dump on your array will give you an exact idea on what type the array value is.
Hope this helps:
<?php
//you might want to convert the JSON string to an array:
$json = '{"1":"http://localhost:8888/classecar/uploads/dropzone/ferrari1.jpg","2":"http://localhost:8888/classecar/uploads/dropzone/ferrari2.jpg","3":"http://localhost:8888/classecar/uploads/dropzone/ferrari3.jpg","4":"http://localhost:8888/classecar/uploads/dropzone/ferrari4.jpg"}';
$array = json_decode($json);
var_dump($array);
// here you already have the json converted to an php array
$arrayWithoutStrangeIndexes = [];
foreach($array as $index => $content){
$arrayWithoutStrangeIndexes[]= $content;
}
// here is just your array with plain data
var_dump($arrayWithoutStrangeIndexes);

Could not convert json string to array using PHP

I need one help. I am unable to convert string to json array using PHP. I am explaining my code below.
$education=$_POST['education'];
the above line give this output [{'name':'aaa','id':'12'},{'name':'bbb','id':'20'}]. But its coming as a string .I tried to convert into array like below but it gived output as null
$edu=json_decode($education,true);
print_r($edu);
It gives the empty output. Here I need to convert it to array and populate all data. Please help me.
Hi You need to make your json string like below:
$arr = '[{"name":"aaa","id":"12"},{"name":"bbb","id":"20"}]';
$a = json_decode($arr);
echo "<pre>";
print_r($a);
die;
it will show your output like below:
Array
(
[0] => stdClass Object
(
[name] => aaa
[id] => 12
)
[1] => stdClass Object
(
[name] => bbb
[id] => 20
)
)
In php, you can use this function to check valid json:
function _isJsonString($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
You can also check online for valid json: http://json.parser.online.fr/
Hope this will help.

IOS Dictionary to php array

I have IOS dictionary like
[{\"my_id_one\":16403,\"my_id_two\":7239}]
When I decode using json_decode, it returns null.
What is best way to decode it to convert it to a PHP array?
Take a look at stripcslashes():
$str = '[{\"my_id_one\":16403,\"my_id_two\":7239}]';
$str_unescaped = stripcslashes($str);
$array = json_decode($str_unescaped, true);
print_r($array);
This outputs:
Array ( [0] => Array ( [my_id_one] => 16403 [my_id_two] => 7239 ) )

PHP Extract only a specific portion in a string between two characters

How can i extract only the substring ..\/files\/listo_bfty77a3.jpg from the main string below?
[
{
"name":"..\/files\/listo_bfty77a3.jpg",
"usrName":"Listo.jpg",
"size":188126,
"type":"image\/jpeg",
"searchStr":"Listo.jpg,!:sStrEnd"
}
]
Practically i would need the content starting from the eleventh char and end at the first ".
Thanks in advance
The string you posted is the JSON representation of some data structure. Decode it using the PHP function json_decode(); pass TRUE as its second argument to get arrays back:
$text = '[
{
"name":"..\/files\/listo_bfty77a3.jpg",
"usrName":"Listo.jpg",
"size":188126,
"type":"image\/jpeg",
"searchStr":"Listo.jpg,!:sStrEnd"
}
]';
$data = json_decode($text, TRUE);
If you don't speak JSON or the data structure is thick and the JSON cannot be understood at the first glance, use print_r() to see how the data structure looks like.
print_r($data);
It displays:
Array
(
[0] => Array
(
[name] => ../files/listo_bfty77a3.jpg
[usrName] => Listo.jpg
[size] => 188126
[type] => image/jpeg
[searchStr] => Listo.jpg,!:sStrEnd
)
)
It's clear now that the property you need can be accessed as $data[0]['img'].

Categories