Accessing loaded json data

Questions and problems about using polymake go here.
meisterniki
Posts: 1
Joined: 25 Oct 2024, 11:48

Accessing loaded json data

Postby meisterniki » 25 Oct 2024, 11:56

Dear forum,

I created a custom object, added fields to it, and saved it with save_data() in json-format. Now I want to load that json and access the saved attributes again. For that I use load_data(). Unfortunately I can't figure out how to correctly access these nested data properties in the json after loading the file. I know that the file got loaded correctly (tested through saving the newly created object which was initialized with load_data()). Attached you find the json:

JSON:
{
"_ns": { "polymake": ["https://polymake.org", "4.13"] },
"data": {
"faces": {
"_type": null,
"data": [
{ "_type": "common::Set<Int>", "data": [0, 2, 4, 6] },
{ "data": [1, 3, 5, 7], "_type": "common::Set<Int>" },
{ "data": [0, 1, 4, 5], "_type": "common::Set<Int>" },
{ "_type": "common::Set<Int>", "data": [2, 3, 6, 7] },
{ "data": [0, 1, 2, 3], "_type": "common::Set<Int>" },
{ "_type": "common::Set<Int>", "data": [4, 5, 6, 7] }
]
}
},
"_type": null
}

My goal is to access data.faces.data .
I am thankful for any help on this issue.

Best regards, Niklas

blorenz
Developer
Posts: 141
Joined: 10 Jan 2011, 17:21

Re: Accessing loaded json data

Postby blorenz » 25 Oct 2024, 12:08

The loaded object is a perl hash reference, and at the key faces it has a perl array reference, so for accessing these need to be dereferenced, e.g. with arrows. The data key is only used internally.

You can access the sets like this:

Code: Select all

polytope > $x = load_data("obj.json"); polytope > print $x->{faces}->[0]; {0 2 4 6} polytope > print $x->{faces}->[1]; {1 3 5 7}
Or the whole array like this:

Code: Select all

polytope > @x = @{$x->{faces}}; polytope > print join(" ", @x); {0 2 4 6} {1 3 5 7} {0 1 4 5} {2 3 6 7} {0 1 2 3} {4 5 6 7}
Benjamin


Return to “Helpdesk”