I
I
Ilya2019-04-22 00:52:06
JSON
Ilya, 2019-04-22 00:52:06

How to organize select for JSON?

Hello!
There is data in JSON format as a file.
Example: there are many vehicle objects (V), each of which has its own manufacturer, color, etc. For each vehicle object, you can select the type: motorcycle or car. Each type of vehicle has its own properties that hypothetically do not change, for example, the maximum speed. So in JS I would write something like this:

var type_1 = {
    max_speed: 300
  },
  type_2 = {
    max_speed: 260
  },
  transport_1 = {
    color: "red",
    type: type_2
  },
  transport_2 = {
    color: "blue",
    type: type_1
  }
}

In general, something like this. So then I could find out the maximum speed of the transport_2 object: transport_2.type.max_speed, but I can’t do this in the json file, links to objects are wrong, just stupid text. Now I open the json file through php and output the layout through the template engine, I just need to do a select for these vehicles objects so that I can select the type of this vehicle, so I don’t understand how I can organize this whole thing so that the object TS knew what type he was. Anyone with experience please share. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
dollar, 2019-04-22
@ravewave

Do not make circular references
var data = {
  types: {
    type_1: {
      max_speed: 300
    },
    type_2: {
      max_speed: 260
    }
  },
  TC: {
    transport_1: {
      color: "red",
      type: "type_2"
    },
    transport_2: {
      color: "blue",
      type: "type_1"
    }
  }
}

var tc = data.TC.transport_1;
console.log("Car:", tc.color); //red
console.log("Speed:", data.types[tc.type].max_speed); //260
Then there will be no problems in JSON
{
  "types": {
    "type_1": {
      "max_speed": 300
    },
    "type_2": {
      "max_speed": 260
    }
  },
  "TC": {
    "transport_1": {
      "color": "red",
      "type": "type_2"
    },
    "transport_2": {
      "color": "blue",
      "type": "type_1"
    }
  }
}
As well as in PHP when working with JSON

PHP: json_decode()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question