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

Time:06-15

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?

CodePudding user response:

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\" }"

CodePudding user response:

This should also work in Python:

#given a JSON and a position to copy, 
#it (line by line) performs:
#(1) transforms it to a Python dictionary
#(2) takes its key
#(3) takes its value
#(4) creates the new key with '
#(5) creates a dictionary with (key':val) 
#(6) translated the new dict to a JSON
#(7) returns the JSON

def take_secondValue(orig_JSON, pos):
  to_Dict = json.loads(orig_JSON)
  ident_key = list(to_Dict.keys())[pos]
  ident_val = list(to_Dict.values())[pos]
  new_key = ident_key "'"
  new_dict = {new_key : ident_val}
  out_JSON = json.dumps(new_dict)
  return out_JSON
  • Related