0

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?

Theo Deep
  • 666
  • 4
  • 15
  • 1
    JSON is a "lightweight data-interchange format", not a programming language. To do any kind of transformation on some input JSON, you would need to use a language like JavaScript or C#. – JamesFaix Jun 15 '22 at 13:43
  • Precisely. How can I make that kind of transformations using, for instance, Python? – Theo Deep Jun 15 '22 at 14:37

2 Answers2

1

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\" }"
JamesFaix
  • 8,050
  • 9
  • 37
  • 73
  • Thanks a lot! I don't know much about JavaScript, but I see the methodology is similar to the one I did in Python, i.e., (1) parse from JSON to the programming language, (2) manipulate using the programming language and then (3) parse again to JSON. Thanks again. – Theo Deep Jun 15 '22 at 15:15
0

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
Theo Deep
  • 666
  • 4
  • 15