I need to obtain the key string from JSON - php

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

Related

Get data from JSON file with PHP (empty result with numbers)

I'm trying to get data from the following JSON file using PHP
I Want To Get All URls (link) ,
http://www.google.com
http://www.bing.com
Json
Here is what I tried
PHP
Thanks
You cannot access an object property using a number, it must be a string.
It is much easier to output json_decode as an array, and access properties that way. To do this, put true as the second parameter.
<?php
$json = '
{
"news": {
"name": "yahoo",
"url": "https://yahoo.com"
},
"links": [
{
"id": "1",
"url": "https://google.com"
},
{
"id": "2",
"url": "https://bing.com"
}
]
}';
$decode = json_decode($json, true);
echo $decode['links'][0]['url'];

Reading the Guzzle response with some nested JSON objects

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};

Decoding and looping through PHP JSON array

I have the following deocoded JSON array.
I need to access the "type" inside the context, as well as I need to loop through each of the values in the payload. How do I do that?
{
"RequestHeader":
{
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context" :
{
"type": "friends,circles"
}
"payload" [ {12345},{12345} ,{2345} ]
}
I tried the following, but it doesn't work
$decoded = json_decode($json_string);
for ($i=0;$i<payload.length;++$i)
{
$id=$decoded->payload[$i];
//do some operation with the id
}
First of all the JSON you provided is invalid. Supposedly the valid one should look like this
{
"RequestHeader": {
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context": {
"type": "friends,circles"
},
"payload": [
12345,
12345,
2345
]
}
After you've fixed the problem with JSON provider it will be quite easy to access data
<?php
$json = <<<'JSON'
{
"RequestHeader": {
"mess": "am putting it on my wall....",
"created_time": "2010-08-24T09:01:25+0000"
},
"context": {
"type": "friends,circles"
},
"payload": [
12345,
12345,
2345
]
}
JSON;
$data = json_decode($json, true);
$type = $data['context']['type'];
var_dump($type);
foreach($data['payload'] as $id) {
var_dump($id);
}
Remember to make sure you check that the data actually exists before accessing it, e.g. isset($data['context']['type']) unless you are absolutely sure in it's integrity.
When you use json_decode method, the output will be nested arrays
So for example to access context type you need to do the following
echo $decoded["context"]["type"];
And to loop on payload you need to do the following
for ($i=0;$i<$decoded["payload"].length;++$i)
{
$id=$decoded["payload"][$i];
//do some operation with the id
}

add data to json (php)

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);

Is there an easy way to convert a json-encoded array into a php array of json-encoded objects?

I have a json string similar to
{
{
"field": value,
"other_field": value,
"object field": {
"field": stuff
}
},
{
"field": value,
"other_field": value,
"object field": {
"field": stuff
}
}
}
and I need to convert it into an array of json strings, so each element of the output array is similar to
{
"field": value,
"other_field": value,
"object field": {
"field": stuff
}
}
I know there's json_decode(), but that will turn the entire thing into a bunch of nested arrays, but I only want to do that to the top level. Is there an easy way to do this, or am I better off decoding the whole string and re-encoding each element?
You have to decode the json string, then encode each array element:
$arr = json_decode($json);
$res = array();
foreach ($arr as $entry) {
$res[] = json_encode($entry);
}
json_decode( $json )[0] to get the first array element. Does this satisfy what you're looking for?
I think you'll have to rethink what you're doing because it's fishy. Here's one solution to what you're asking though:
<?php
$json = '[ {"foo": 1, "bar": true}, {"foo": 2, "bar": false} ]';
array_map('json_encode', json_decode($json));
// Array
// (
// [0] => {"foo":1,"bar":true}
// [1] => {"foo":2,"bar":false}
// )

Categories