SharedArray function question

Hello folks. I have a question about a use of sharedArray that is giving me grief…

given this datafile seed_data.json…

{
    "rampup_peak":
    [
        {
            "key": "4m",
            "weight": 1
        }
    ],
    "duration_peak": [
        {
            "key": "14m",
            "weight": 1
        }
    ]
}

when I try to access the file with SharedArray in the follow way

let KEY = 'rampup_key'

const seed_file = new SharedArray('Accounts', function () {

return JSON.parse(open('../../data/seed_data.json')).KEY;

});

I get this error

          /\      |‾‾| /‾‾/   /‾‾/   
     /\  /  \     |  |/  /   /  /    
    /  \/    \    |     (   /   ‾‾\  
   /          \   |  |\  \ |  (‾)  | 
  /______ \  |__| \__\ \_/ .io

TypeError: Cannot read property 'KEY' of undefined

here’s my current silly question… is a global variable KEY not accessible within a javascript function return? KEY is clearly defined but the variable is out of scope within the SharedArray function to open the file and access the JSON within.

Doesn’t appear to be a SharedArray issue. just whether a variable can used to represent a KEY within a JSON object.

this returns undefined as well.

let keys = JSON.parse(open('../../data/seed_data.json')).$KEY;

let data_key = JSON.stringify(rampup_peak[0].key)

Here is a more generic rendition of my question… How do I pass “key1” or “keys2” as a variable to JSON.parse(json)? I used - Mozilla to test this.

const json = '{"keys1":[{"result":true, "count":42}],"keys2":[{"result":false, "count":43}]}';

const obj = JSON.parse(json).keys1;

console.log(obj[0].count);
// expected output: 42

console.log(obj[0].result);
// expected output: true

Hi @PlayStay,

Your question is basically how do I get an object property by a variable key and the answer is that you need to use the bracket notation

JSON.parse(open('../../data/seed_data.json'))[KEY];

:poop: :balls… I"m going to go crawl into a hole now… Thanks @mstoykov

1 Like