0

I have one json object and one array as follows:

a = [{"id":1,"content":"aaa"},{"id":2,"content":"bbb"}];
b = ["a.jpg","b.jpg"];

Now i want to create one more json object which points to this json and array , Something like :

c = [{groupId:1,
      "group":[{"aId":pointer to a json,"bId":pointer to b array
              },{"aId":pointer to a json,"bId":pointer to b array
              }]
    }];

Is it possible in javascript??

4

3 回答 3

6

You cannot do that (have pointers or references in JSON notation).

You may define your own convention, such (for example), that a JSON object like {"refId": 1} means to your applications to be some "pointer" to the thing decoded with the JSON "id":1 but you have to code for that.

FWIW, the YAML notation has references (with anchors and aliases)

于 2013-05-07T06:50:54.157 回答
5

There is a proposed standard RFC 6901: JavaScript Object Notation (JSON) Pointer, which introduces a concept of a pointer in JSON structure.

Here is an example taken from the RFC:

For example, given the JSON document

{
  "foo": ["bar", "baz"],
  "": 0,
  "a/b": 1,
  "c%d": 2,
  "e^f": 3,
  "g|h": 4,
  "i\\j": 5,
  "k\"l": 6,
  " ": 7,
  "m~n": 8    }

The following JSON strings evaluate to the accompanying values:

""           // the whole document
"/foo"       ["bar", "baz"]
"/foo/0"     "bar"
"/"          0
"/a~1b"      1
"/c%d"       2
"/e^f"       3
"/g|h"       4
"/i\\j"      5
"/k\"l"      6
"/ "         7
"/m~0n"      8

There are also some packages available that support this RFC, like json-pointer.

于 2017-09-06T18:17:09.070 回答
4

Theoretically it would be possible, but as soon as you send the json to a different machine, the pointers would be invalid.

You have 2 possibilities to solve the problem:

  1. nest the array and the json in the original json

  2. reference the array and json by some sort of ID. This second approach need more work on both the sending and receiving side, but reduces the amount of space used by your json.

于 2013-05-07T06:52:15.317 回答