user10300637
user10300637

Reputation:

Add Key to Value in JSON with PHP

An API I'm using formats its JSON without a KEY to the object values. It's formatted more like an array. For reference, here's a link to the API I'm attempting to use https://opensky-network.org/apidoc/rest.html. Below is an example of what that JSON looks like.

Wrong example

{
    "time": 1535758880,
    "states": [
        [
            "First",
            "A"
        ],
        [
            "Second",
            "B"
        ]       
    ]
}

The above JSON also has square brackets for each object. Which doesn't work in my situation. They need to be curly brackets instead. Below is an example of what I'm trying to achieve. Notice that the object brackets are curly and the values have a key for each of them.

Needed Example

{
    "time": 1535758880,
    "states": [
        {
            "id": "First",
            "content": "A"
        },
        {
            "id": "Second",
            "content": "B"
        }       
    ]
}

Here is the code that I'm currently writing to find a value within the JSON.

<?php
$str = '
{
    "time": 1535758880,
    "states": [
        {
            "id": "First" ,
            "content": "A"
        },
        {
            "id": "Second" ,
            "content": "B"
        }       
    ]
}';

$json = json_decode($str);
foreach($json->states as $item)
{
    if($item->id == "Second")
    {
        echo $item->content;  
    }
}
?>

My overall question is, how can I add id and content to my JSON and also replace the the square brackets for each object with curly brackets? I'm thinking that I need do a str_replace() somehow. But I'm not really sure how to approach this.

Upvotes: 1

Views: 1737

Answers (2)

aron.duby
aron.duby

Reputation: 2290

Definetly don't try string replace.

First off I would question if you really need that conversion from an array to an object. $item[0] not much worse than $item->id. If you really want to you could make your code more obvious and make variables for the indexes.

$id = 0;
$content = 1;

if ($item[$id] == 'Second') {
    echo $item[$content];
}

But if for whatever reason you a stuck having to convert you can use the code in mopsyd post above

Upvotes: 0

mopsyd
mopsyd

Reputation: 1922

You need to recast the array, and then re-encode it back to json. Something like this:

$formatted = json_decode($str);
foreach ($formatted->states as $key => $value) {
    $tmp = array(
        'id' => $value[0],
        'content' => $value[1]
    );
    $formatted->states[$key] = $tmp;
}

// If you want this in array format you are done here, just use $formatted.

// If you want this back in json format, then json_encode it.
$str = json_encode($formatted);

Upvotes: 1

Related Questions