jsonidentityto-json

In JSON, how to create a basic identity of one of the value


I have no idea about JSON (nor YAML), so I would like to start with a very simple 'identity' operation: formed by a two-pair object, how can I return another JSON that makes the identity of the value of one of the two pairs?

For example, given {"a": a, "b":b}, how can I read that and return a JSON whose content is {"b'":b}? I only think I know how to represent the input JSON (and the output JSON), but I don't know how to relate them so that the input 'b' is also in the output.

I am looking for an "implementation" of this that is something like a function that receives a JSON and returns a JSON. I do not know if this can be done within JSON or we need a programming language and use a toJSON like.

Any help? Also, where can I learn similar very fundamental concepts of JSON?


Solution

  • Here is a JavaScript solution. You can try this out in your browser console.

    let json = "{ \"a\": \"a\", \"b\": \"b\" }";
    let obj = JSON.parse(json);                     // { a: 'a', b: 'b' }
    let entries = Object.entries(obj);              // [ ['a', 'a'], ['b', 'b'] ]
    let secondEntry = entries[1];                   // ['b', 'b']
    let newObj = Object.fromEntries([secondEntry]); // { b: 'b' }
    let newJson = JSON.stringify(newObj)            // "{ \"b\": \"b\" }"