for example if I have a simple JSON like this:
{
"data": [
"pets" : "none",
"parents": {"mom":"Anna", "dad":"Bob"},
"ancestors": { "children":[
{
"name": "Joe",
"age" : "10"
},
{
"name" : "Ron",
"age" : "4"
}
]}
]
}
and let's say I want to add a child "Jessica" of age "8" with PHP
how would i do that?
so far I know i need to use json_decode to access the JSON, json_encode to save something in it
but if I need to add a $newchild = array("name" : "Jessica", "age" : "8"); and add it how would it do it in data->ancestors->children ?
When you use json_decode, you are converting the json string to php array
So, you can add the new element like so:
$jsonstring = '...the string...';
$jsonarray = json_decode($jsonstring, true);
$jsonarray['data']['ancestors']['children'][] = array('name'=>'Jessica', 'age'=>8);
Make print_r of the $jsonarray to see it's contents
and then of course you could print it again to json string
$jsonstring = json_encode($jsonarray);
Related
I have this JSON in a request for an laravel API:
{
"questionary": {
"directLeader": {
"answer": "ALWAYS",
"comments": "asdf"
}
},
"id": 14
}
I need to obtain the string "directLeader" 'cause this key changes in the request and I used that as a reference for a query update.
To convert json to array:
$array = json_decode($json, true);
To get the first key inside associative array:
$firstKey = array_key_first($array['questionary']);
$firstKey will contain your dynamic key.
You need to json_decode() the json you have like so
$json = '{
"questionary": {
"directLeader": {
"answer": "ALWAYS",
"comments": "asdf"
}
},
"id": 14
}';
$encoded_json = json_decode($json, true);
dd($encoded_json['questionary']['directLeader']);
Note
the true in json_decode() will convert the object to array, without true it will an object
My json file look likes
myjson.json
[
{"name":"category_01","data":
[
{"id":"1","word":"ma","given_value":"1"},
{"id":"3","word":"me","given_value":"1"},
] }
[
{"name":"category_02","data":
[
{"id":"1","word":"vea","given_value":"1"},
{"id":"3","word":"ve","given_value":"1"},
] }
So what I want here is, check whether a particular value is in this json array using php. Assume that,
myphp.php
$word = 've';
if this value is in the above array, should find is it in category_01 or category_02. and also want to find given_value of matching word.
I just tried in this way,
$data = file_get_contents ("myjson.json");
$json = json_decode($data, true);
foreach($arr as $item) {
$uses = ($item['word']= $word);
}
This doesn't work. How can I fix this, Please help me!
First of all, the JSON you posted is invalid. I think it should look like this:
[
{
"name": "category_01",
"data": [{
"id": "1",
"word": "ma",
"given_value": "1"
},
{
"id": "3",
"word": "me",
"given_value": "1"
}
]
},
{
"name": "category_02",
"data": [{
"id": "1",
"word": "vea",
"given_value": "1"
},
{
"id": "3",
"word": "ve",
"given_value": "1"
}
]
}
]
Try using on online tool like https://jsonlint.com/ to check your JSON. (if you get errors i recommend build the json again from scratch).
I also recommend checking your json before using it:
if ($arr === null && json_last_error() !== JSON_ERROR_NONE) {
die("incorrect json data");
}
To get your value you have to KNOW how your data looks like and then process it:
foreach($arr as $category) {
foreach($category['data'] as $data) {
if(strstr($data['word'], $word))
echo $category['name'].' '.$data['word'].' '.$data['given_value']."\n";
}
}
I have made a http request to my api using Guzzle library as follow :
$client = new Client();
$response = $client->request(
'GET',
config('some_url');
$serverResponse = json_decode($response->getBody(),true);
if ($serverResponse['result']) {
$data = $serverResponse['data'];
Now I got the response as
{
"result": true,
"data": {
"101": {
"id": 101,
"name": "ABCD",
"age" : 24
},
"102": {
"id": 102,
"name": "EFGH",
"age" : 24
},
"103": {
"id": 103,
"name": "IJKL",
"age" : 24
},
}
}
The problem is I need to read and push the object models 101,102,103 to a separate array. for this I try to get the objects as following options. but I could not able to get the results rather than errors.
$obj = $data[0];
It returns Undefined offset: 0 error
Because your data is being manually indexed, as opposed to something like:
{
"data": {
0: {
"id": 101,
...
},
1: {
"id": 102,
...
},
...
}
}
You will need to specify these indexes when fetching the data. E.g:
$data["101"]
To do this for dynamically set data you can use array_keys
$obj = $data[array_keys($data)[0]];
Using array_keys allows you to search $data by the numerical index of $data
If you simply want to re-index the array so that the keys are [0], [1], [2], etc. you can use the following:
$newArray = array_values($data);
You will then be able to access the first sub-array with $newArray[0], the second with $newArray[1], etc.
You can convert the response to object and then you can access the properties as following.
$obj = json_decode($response->getBody());
$one_zero_one = $obj->data->{101};
can someone please help me to add data to following json.
$temp='{
"custId": 123,
"data": [
{
"code": "abc1"
},
{
"code": "abc2"
}
],
"id": 102
}';
data to be added
$data1='{
"code": "abc3"
}';
Desired result
$temp='{
"custId": 123,
"data": [
{
"code": "abc1"
},
{
"code": "abc2"
},
{
"code": "abc3"
}
],
"id": 10
}';
I can append data to $temp, but can someone please help to add data to specific position with php. Thank you in advance. (I've tried json_decode($temp, true) and then finding the location where data1 is to be added but failed).
You can convert your data to a normal PHP array:
$array = json_decode($temp, true);
then just add or change anything you want:
$array["data"][] = array(["code"] => "abc3");
and re-encode to json:
$temp = json_encode($array);// encode to json
http://php.net/manual/en/function.json-decode.php
first, you need to convert the JSON into PHP array like this:
$array = json_decode($temp, true);
Then, it's as simple as:
$array['data']['code'] = 'abc3';
If the string that you want to add is still a JSON, you have to convert that one in an array as well so:
$arr_to_add = json_decode($data1, true);
$array['data'][] = $arr_to_add;
In the end, of course, encode again like this:
$final_json = json_encode($array);
Hope this helps! :D
First you need to decode the json with json_decode. This returns a PHP variable.
Add desired values.
Use json_encode to get the json with new values. Returns a string containing the JSON.
you can try this:
<?php
$temp='{
"custId": 123,
"data": [
{
"code": "abc1"
},
{
"code": "abc2"
}
],
"id": 102
}';
$data1='{
"code": "abc3"
}';
$jarr=json_decode($temp,true);
$appArr=json_decode($data1,true);
$desire=array_merge($jarr,$appArr);
//print_r($desire);
echo json_encode($desire);
so take this as the url output from the browser.
{
"data": {
"detections": [
[
{
"language": "en",
"isReliable": false,
"confidence": 0.5714286
}
]
]
}
}
now i need to get "en" value from the returned values
i tried:
$from = $json->data->detections->language;
still none work. what am i missing here ?
$json = json_decode(file_get_contents($detect));
It is
$json->data->detections[0][0]->language;
Get var_dump($json); and see the actual structure