Viewed   90 times

I have the following JSON file as input,

{
  "$type": "NanoWebInterpreter.WebInputData, NanoWebInterpreter",
  "NBBList": {
    "$type": "System.Collections.Generic.List`1[[monoTNP.Common.NBB, monoTNP.Common]], mscorlib",
    "$values": [
      {
        "$type": "monoTNP.Common.NBB, monoTNP.Common",
        "ID": "id-0065-00000003",
        "MPList": {
          "$type": "System.Collections.Generic.List`1[[monoTNP.Common.MP, monoTNP.Common]], mscorlib",
          "$values": [
            {
              "$type": "monoTNP.Common.EllipticalMP, monoTNP.Common",
              "Eccentricity": 1.0,
              "ID": "id-0065-00000006",
              "ParticleIndex": -1,
              "DispersionInteractionStrength": 0.0,
              "DispersionInteractionRange": 2.5,
              "CharacteristicSize": 0.0,
              "CenterOfMass": "<0,0,0>",
              "OrientationVector": "<>"
            },
            {
              "$type": "monoTNP.Common.CubeMP, monoTNP.Common",
              "ID": "id-0065-00000005",
              "ParticleIndex": -1,
              "DispersionInteractionStrength": 0.0,
              "DispersionInteractionRange": 2.5,
              "CharacteristicSize": 0.0,
              "CenterOfMass": "<0,0,0>",
              "OrientationVector": "<>"
            },
            {
              "$type": "monoTNP.Common.CircularMP, monoTNP.Common",
              "ID": "id-0065-00000004",
              "ParticleIndex": -1,
              "DispersionInteractionStrength": 0.0,
              "DispersionInteractionRange": 2.5,
              "CharacteristicSize": 0.0,
              "CenterOfMass": "<0,0,0>",
              "OrientationVector": "<>"
            }
          ]
        },

etc.

My ultimate goal is to trace this tree recursively, wrapping each key/object name with <ul> tags, and the properties at the "ParticleIndex" level in some kind of <form> structure, but I can't figure out how to index into the two '$values' arrays.

This is the code that I have been manipulating to learn how each element(object or array) is accessed:

foreach ($json->NBBList->'$values'[0] as $key => $value){
    var_dump($key);
    echo "n".var_dump($value);
    echo "nnn";
}

This obviously doesn't work because the index of values is outside of the string, but when it is on the inside, PHP interprets it as part of the string.

Is there a way for me to index into each element of the '$values' array, and ultimately in a for loop?

I'm thinking using the "true" property of JSON decode might be a better solution...

 Answers

5

You can access object properties with names that contain special characters using this notation:

$json->NBBList->{'$values'}[0]

I don't think that this behavior is documented anywhere, but you can find it in the PHP grammar (see definition of variable_name, which is used in object_dim_list, which is used in object_property).

Wednesday, September 14, 2022
 
5

In order to update charts that way, you need to create chart only once (outside the ajax request) and keep adding new dataPoints via ajax request each second as shown below.

<!DOCTYPE HTML>
<html>
    <head>  
        <script type="text/javascript" src="canvasjs.min.js"></script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <script>
            $(document).ready(function () {
                var chart = new CanvasJS.Chart("chartContainer", {

                    zoomEnabled: true,
                    panEnabled: true,
                    animateEnabled: true,
                    data: [ {
                        type: "splineArea",
                        xValueType: "label",
                        y: "y",
                        dataPoints: [] 
                    } ] 

                });

                function updateChart(){
                    $.getJSON("data.php", function (data_points) {
                        for(var i = 0; i < data_points.length; i++){
                            chart.options.data[0].dataPoints.push(data_points[i]);
                        }

                        chart.render();
                    });
                }               

                var updateInterval = 1000;

                setInterval(function(){
                        updateChart()
                }, updateInterval);

            });

        </script>
    </head>
    <body>
        <div id="chartContainer" style="height: 300px; width: 500px;"></div>
    </body>
</html>
Friday, December 2, 2022
 
2

json_decode returns NULL if there is an error in the JSON syntax. I've just successfully tested on an array of 1000 elements and it ran just fine.

Double-check that your JSON is correctly formatted. Even something as small as having single quotes instead of double, or forgetting to put a property name in quotes, or using a character outside the 32-127 range without correctly encoding it in UTF-8 can cause these problems.

Wednesday, September 14, 2022
 
1

Given this JSON, you can get the currency of a country as follows:

function getCurrencyFor($arr, $findCountry) {
    foreach($arr as $country) {
        if ($country->name->common == $findCountry) {
            $currency = $country->currency[0];
            break;
        }
    }
    return $currency;
}

$json = file_get_contents("https://raw.githubusercontent.com/mledoze/countries/master/countries.json");
$arr = json_decode($json);
// Call our function to extract the currency for Angola:
$currency = getCurrencyFor($arr, "Angola");

echo "Angola has $currency as currency";
Sunday, October 30, 2022
 
4

you can use it like this, in JSON format when you evaluate false value it will give you blank, and when you evaluate true it will give you 1.

$str = '[{"clientId":"17295c59-4373-655a-1141-994aec1779dc","channel":"/meta/connect","connectionType":"long-polling","ext":{"fm.ack":false,"fm.sessionId":"22b0bdcf-4a35-62fc-3764-db4caeece44b"},"id":"5"}]';

$arr = json_decode($str,true);

if($arr[0]['ext']['fm.ack'])    // suggested by **mario**
{
    echo "true";    
}
else {
    echo "false";   
}
Thursday, October 6, 2022
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :