How to get a key value in a json object and affect it into the same object?

时间:2019-04-25 10:15:33

标签: json object variables

I have a json object with some keys and values. I would like to get a generic way to get one of these values and set (into the same object) a variable with this value.

myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "key":"John",
    "car2":"BMW",
    "car3":"Fiat"
  }
 }

myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "other-name":"John",
    "car2":"BMW",
    "car3":"Fiat"
  }
 }

3 个答案:

答案 0 :(得分:0)

您可以使用object.property.anotherProperty表单或object [“ property”] [“ anotherProperty”]访问表单来读取和设置值,例如:

myObj.cars.car2 = myObj.cars.car3;

P.S。假设使用Java

答案 1 :(得分:0)

您可以如下分配新值。

myObj.cars.newKey =“任何值”

答案 2 :(得分:0)

这是一个很好的答案,但是我想知道我何时在vi上的jsonfile中写入