For inspiration, you may want to look into the way some of the json based api's (ex: json api, HAL) handle embedding.

One simple answer is to track your data in a key value store. For example

{ "/players/0" : {...}
, "/players/1" : {...}
, "/players/2" : {...}
, "/players/3" : {...}
, "/teams/0" : {...}
, "/teams/1" : {...}
}

And then you describe the players assigned to your team using local references

, "/teams/0" :
    { refs : 
        [ "/players/0"
        , "/players/1"
        ]
    }

As it happens, this scheme covers the case where you have identifiers too. Or where you only have some identifiers

, "/teams/0" :
    { refs : 
        [ "/players/0"
        , "/players/2ad8cabe-2f93-11e6-ac61-9e71128cae77"
        ]
    }

There are fancier versions of this idea (see the links).

That said, I've been down this road myself, and I really tied myself in knots until I concluded: if what you really have is a list of names, rather than a list of players, admit that to yourself, code it that way, and deal with it. It's the more honest way of representing what's going on in the domain at that point in time.

In which case, the payload of your message should look very close to:

{ "Team 1" : 
  [ "Player 1"
  , "Player 2"
  ]
, "Team 2" :
  [ "Player 3"
  , "Player 4"
  ]
}

If that makes you twitchy, remember: this isn't a description of your domain objects; it's a message. The changes it makes to your domain are a side effect. Jim Webber covers this in the introduction to this talk.

Answer from VoiceOfUnreason on Stack Exchange
🌐
Readthedocs
json-spec.readthedocs.io › reference.html
JSON Reference — JSON Spec documentation - Read the Docs
from jsonspec.reference import Registry from jsonspec.reference.providers import FileSystemProvider obj = { 'foo': {'$ref': 'my:doc#/sub'} } provider = FileSystemProvider('/path/to/my/doc', prefix='my:doc') resolve(obj, '#/foo/2', { 'obj2': {'sub': 'quux'} }) ... Register all documents. ... Resolve from documents. class reference.LocalRegistry(doc, provider=None)¶ · Scoped registry to a local document. ... Extracts $ref of object.
Top answer
1 of 3
9

For inspiration, you may want to look into the way some of the json based api's (ex: json api, HAL) handle embedding.

One simple answer is to track your data in a key value store. For example

{ "/players/0" : {...}
, "/players/1" : {...}
, "/players/2" : {...}
, "/players/3" : {...}
, "/teams/0" : {...}
, "/teams/1" : {...}
}

And then you describe the players assigned to your team using local references

, "/teams/0" :
    { refs : 
        [ "/players/0"
        , "/players/1"
        ]
    }

As it happens, this scheme covers the case where you have identifiers too. Or where you only have some identifiers

, "/teams/0" :
    { refs : 
        [ "/players/0"
        , "/players/2ad8cabe-2f93-11e6-ac61-9e71128cae77"
        ]
    }

There are fancier versions of this idea (see the links).

That said, I've been down this road myself, and I really tied myself in knots until I concluded: if what you really have is a list of names, rather than a list of players, admit that to yourself, code it that way, and deal with it. It's the more honest way of representing what's going on in the domain at that point in time.

In which case, the payload of your message should look very close to:

{ "Team 1" : 
  [ "Player 1"
  , "Player 2"
  ]
, "Team 2" :
  [ "Player 3"
  , "Player 4"
  ]
}

If that makes you twitchy, remember: this isn't a description of your domain objects; it's a message. The changes it makes to your domain are a side effect. Jim Webber covers this in the introduction to this talk.

2 of 3
4

This is a really nice question.

The problem arises because you are modeling redundant information and try to avoid redundancy at the same time.

On the one hand, you have a collection of players

players = [{"id":"1"},{"id":"2"},{"id":"3"}]

On the other hand, you have a colletion of teams, which itself consist of subsets from players.

teams = [ {"id":"1", "players": [ players[0], players[1] ]} ]

This gives a composition:

players = [{id:1},{id:2},{id:3},{id:4}]

teams =[ {id:1, players:[players[0], players[1]]} ]

data = {players:players, teams:teams}

Look here for the Fiddle and watch the result.

As you see, the references cause redundant information in JSON.stringify, because you have redundant information in your data object.


The problem of avoiding redundancy arises when sending data to the server.

Take a step back.

What do you want to tell the server?

a) Here you have a list of teams, please persist it for me. I come back to you later. Oh, by the way, the teams contain the following players blablabla

b) Here you have a list of players. Keep 'em safe for me. I need them later to build `teams.

Your model shows, that you are not clear.

There are several usecases:

I) I want to create new players

IIa) I want to create new teams

IIb) I want to put players in teams

I) In a REST-context, you could issue a POST to /players.

IIa,b) You POST to /teams your collection of teams.

How to deal with the situation, that you want to save requests and do not issue a single POST for each creation of a new player (and an additional one for submitting the team)?

I would go for the following:

You have a collection of players: some of them have an id, indicating, that they were already persisted; some of them don't.

If you create teams, you issue only one POST request with the teams, containing the full player objects.

[{"name":"team1", "players":[{"id":"1", "name":"player1"}, "name":"player2"}]}, ... ] // you get the idea 

The server isn't interested in knowing explicitely how many players there are: it is implicitely clear: it's the sum of all players (which might be the sum of all players in all teams).

The server has to figure out, how to persist the players and how to set foreign keys (in case of relational DBs).

Discussions

json - Standard way of referencing an object by identity (for, eg, circular references)? - Stack Overflow
Still, it seems to be used in JSON Schema and Swagger (now OpenAPI) (for reusing parts of an API description in other places of the same or another API description). A reference to an object in the same file looks like this: { "$ref": "#/definitions/Problem" }. More on stackoverflow.com
🌐 stackoverflow.com
Are references possible in JSON?
Javascript doesn't have explicit objects references. What are you trying to do? ... I will traverse those values and perform some operations like changing name of the person. ... If this is about JSON, then it does not have anything to do with JavaScript, and vice versa. More on stackoverflow.com
🌐 stackoverflow.com
I need to set a json object property in a object, then reference that property from another object in the same object
I have this issue, I want to be able to change the audio being used based on the browser. What I have is an object seen below, which has a "ext: { sound: '.mp3' }", at some point I will make some More on stackoverflow.com
🌐 stackoverflow.com
[JSON] Is it possible to self-reference values in a JSON declaration?

No, JSON is essentially represented as a string. Nodes JSON.stringify will attempt to convert 100 + this.armour to a primitive value (in this case NaN), but other implementations of stringifywould perhaps render it as a single string that when parsed would result in a string "100 + this.armour".

If I were you, I would store the stringified object only with values that can be represented as primitive values. Then, when you parse the JSON string into a JS object, pass it into a function that will compute the additional properties that rely on other properties.

More on reddit.com
🌐 r/javascript
34
8
May 8, 2016
🌐
Redocly
redocly.com › learn › openapi › ref-guide
How to use JSON references ($refs)
May 28, 2025 - Reference a definition within a file by remote URL and pointer to the object. Use a JSON Pointer to the object.
🌐
Niem
niem.github.io › json › reference › json-schema › references
JSON References | NIEM GitHub
Here is an example JSON schema ns.schema.json including cross-schema references to types in xs.schema.json, a schema in the same directory, and in-schema references to types and properties in the same schema: { "$id": "http://release.niem.gov/niem/niem-core/4.0/", "$schema": "http://json-schema.org/draft-04/schema#", "type": "object", "additionalProperties": false, "definitions": { "nc:Amount": { "$ref": "./xs.schema.json#/definitions/xs:decimal", "description": "An amount of money."
Top answer
1 of 3
2

what your trying to do is not possible.

the object has to be initialized before its values can be referred to

you could use a function inside the object.

or change the initial val of StAd0.src to '' or 'ar/55871' then reset that value after you set the var object; to object.StAd0.src = 'ar/55871'+ object.ext.sound;

var object = {
ext: {
    sound: '.mp3'
    },
pref: {
    acc: 1
},
StAd0: {
    from: 25,
    to: 180,
    src: 'ar/55871',
    du: 5228
},
Image_33: {
    type: 15,
    from: 4,
    to: 48,
    rp: 0,
    rpa: 0,
    mdi: 'Image_33c',
    trin: 6,
    trout: 6,
    ef: {}
},
Image_33c: {
    b: [171, 259, 850, 360],
    ip: 'dr/7029_679_101.png',
    dn: 'Image_33',
    visible: 1,
    accstr: 'Image ',
    vb: [171, 259, 850, 360]
}
};
 object.StAd0.src = 'ar/55871'+ object.ext.sound;
2 of 3
1

Then src must be a function.

var object = {
    ext: {
        sound: '.mp3'
        },
    pref: {
        acc: 1
    },
    StAd0: {
        from: 25,
        to: 180,
        src: function() {
            return 'ar/55871'+ this.ext.sound;
        },
        du: 5228
    },
    Image_33: {
        type: 15,
        from: 4,
        to: 48,
        rp: 0,
        rpa: 0,
        mdi: 'Image_33c',
        trin: 6,
        trout: 6,
        ef: {}
    },
    Image_33c: {
        b: [171, 259, 850, 360],
        ip: 'dr/7029_679_101.png',
        dn: 'Image_33',
        visible: 1,
        accstr: 'Image ',
        vb: [171, 259, 850, 360]
    }
}

But you must get src like this,

object.stAd0.src();

EDIT:

There isn't anyway to do it without a function, because if you try that like this,

src: ar/55871+ this.ext.sound;

that will work only once at parse-time. Than it will have a static value inside.

If you can't change all src properties to function, you can get it like this as well.

var src = (typeof object.StAd0.src == "function")? object.StAd0.src() : object.StAd0.src;

So If src is defined as a function, it will call it else will take it like a property.

Find elsewhere
🌐
Reddit
reddit.com › r/javascript › [json] is it possible to self-reference values in a json declaration?
r/javascript on Reddit: [JSON] Is it possible to self-reference values in a JSON declaration?
May 8, 2016 -

Hey peeps,

Okay, so, just playing with making a wee CCG and storing the stats in a JSON object, but some of the stats are self-referential and I was wondering if there was a way around this. FOR EXAMPLE :

var cardOne = {
  name : "Example Card",
  armour : 70,
  courage : 100 + this.armour
};

Now, I know that this.armour won't work in this context, but what would?

Any help would be grand. Thanks in advance!

-P


EDIT 1: okay, seeing as this is Chrome-only project I've decided to take advantage of ES6's class notation and implement it like this :

 class Card {
     constructor(_name, _armour){
         name  = _name;
         armour = _armour;
         courage = 100 + _armour;
     }
 }
 var testCard = new Card("Example Card", 70);

...and that's how it'll stay for now, but if you can point me towards a more efficient alternative then that'd be great!


EDIT 2: as u/talmobi/ pointed out, this is the equivalent of simply writing :

var Card = function(_name, _armour){
    this.name = _name;
    this.armour = _armour;
    this.courage = 100 + _armour;
};
var testCard = new Card("Example Card", 70);

Well...that's not exactly what they said, but you can read their full comment here.

🌐
JSON Schema
json-schema.org › understanding-json-schema › structuring
JSON Schema - Modular JSON Schema combination
{ "$id": "https://example.com/... "string" } }, "required": ["street_address", "city", "state"]} · A schema can reference another schema using the $ref keyword....
🌐
GitHub
github.com › java-json-tools › json-schema-validator › issues › 299
How to reference other json file by using $ref? · Issue #299 · java-json-tools/json-schema-validator
May 28, 2019 - How to reference other json file by using $ref? { "level" : "error", "message" : "string is not a valid URI: \"file://C:\\Users\\Tryking\\Desktop\\JsonSchema\\AreaTest.json\"", "domain" : "syntax", "schema" : { "loadingURI" : "#", "point...
Published   May 28, 2019
Author   Tryking
🌐
Opis
opis.io › json-schema › 2.x › references.html
JSON Schema references ($ref) | Opis JSON Schema
In order to reuse the custom email validator we make a reference to it by using the $ref keyword. Let’s see how it will look. ... { "$id": "http://example.com/custom-email-validator.json#", "type": "string", "format": "email", "pattern": "@example\\.test$" } The custom email validator. { "type": "object", "properties": { "name": { "type": "string", "minLength": 2 }, "email": { "$ref": "http://example.com/custom-email-validator.json#" } }, "required": ["name", "email"], "additionalProperties": false }
🌐
W3Schools
w3schools.com › jsref › › jsref_obj_json.asp
JavaScript JSON Reference
JSON is text, and text can be transported anywhere, and read by any programming language. JavaScript Objects can be converted into JSON, and JSON can be converted back into JavaScript Objects.
🌐
Newtonsoft
newtonsoft.com › json › help › html › preserveobjectreferences.htm
Preserving Object References
By default Json.NET will serialize all objects it encounters by value. If a list contains two Person references and both references point to the same object, then the JsonSerializer will write out all the names and values for each reference.
🌐
Thephpleague
json-reference.thephpleague.com
JSON Reference - Resolve JSON References in Swagger, JSON Schema, RAML etc
If you have used Swagger, JSON Schema or RAML to document your API you have probably used JSON references. A JSON reference is a JSON object that looks like {"$ref": "http://some/where"} and points to a JSON object somewhere else so you don’t have to copy and paste it.
🌐
JSON Schema
json-schema.org › understanding-json-schema › reference › object
JSON Schema - object
Objects are the mapping type in JSON. They map "keys" to "values". In JSON, the "keys" must always be strings. Each of these pairs is conventionally referred to as a "property".
🌐
Cswr
cswr.github.io › JsonSchema › spec › definitions_references
Definitions & References - JSON Schema
In order to do this we need to add the address part of the URI in the reference keyword. For example, assume that the URI http://db.ing.puc.cl/exampleschema retrieves the following json document: { "definitions": { "person": { "type": "object", "required": ["first_name", "last_name", "age"], "properties": { "first_name": {"type": "string"}, "last_name": {"type": "string"}, "age": {"type": "integer"} } }, }, "type": "object", "required": ["name", "league"], "properties": { "name": {"type": "string"}, "league": {"type": "string"}, "year_founded": {"type": "integer"} } }
🌐
Stack Overflow
stackoverflow.com › questions › 55928018 › how-to-reference-an-item-in-a-json-object-using-another-item-inside-the-same-obj
python - How to reference an item in a json object using another item inside the same object - Stack Overflow
The fact that you might have gotten this by decoding a JSON value isn't relevant. ... Thanks guys, didnt think about iterating through it to get the desired response @Barmar was correct with what I was looking for ... objects = [ {"Abbv": "VIS", "Set": "Visions"}, {"Abbv": "5ED", "Set": "Fifth Edition"}, {"Abbv": "POR", "Set": "Portal"}, {"Abbv": "WTL", "Set": "Weatherlight"} ] for obj in objects: if obj['Abbv'] == 'VIS': print(obj['Set'])