JSON Object Letterals
Dit is 'n JSON-string:
'{"name":"John", "age":30, "car":null}'
Binne die JSON-string is daar 'n JSON-objek letterlik:
{"name":"John", "age":30, "car":null}
JSON-objekletters word omring deur krulhakies {}.
JSON-objekletters bevat sleutel/waarde-pare.
Sleutels en waardes word deur 'n dubbelpunt geskei.
Sleutels moet stringe wees, en waardes moet 'n geldige JSON-datatipe wees:
- string
- nommer
- voorwerp
- skikking
- boolean
- nul
Elke sleutel/waarde-paar word deur 'n komma geskei.
Dit is 'n algemene fout om 'n JSON-voorwerp letterlik "'n JSON-voorwerp" te noem.
JSON kan nie 'n voorwerp wees nie. JSON is 'n string-formaat.
Die data is slegs JSON as dit in 'n string-formaat is. Wanneer dit na 'n JavaScript-veranderlike omgeskakel word, word dit 'n JavaScript-objek.
JavaScript-voorwerpe
Jy kan 'n JavaScript-objek skep vanaf 'n JSON-objek letterlik:
Voorbeeld
myObj = {"name":"John", "age":30, "car":null};
Normaalweg skep jy 'n JavaScript-objek deur 'n JSON-string te ontleed:
Voorbeeld
myJSON = '{"name":"John", "age":30, "car":null}';
myObj = JSON.parse(myJSON);
Toegang tot objekwaardes
Jy kan toegang tot objekwaardes kry deur die punt (.)-notasie te gebruik:
Voorbeeld
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
x = myObj.name;
U kan ook toegang tot objekwaardes verkry deur hakie ([])-notasie te gebruik:
Voorbeeld
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
x = myObj["name"];
Loop 'n voorwerp
Jy kan deur voorwerpeienskappe loop met 'n for-in lus:
Voorbeeld
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += x + ", ";
}
In 'n for-in lus, gebruik die hakie notasie om toegang tot die eiendom waardes te verkry :
Voorbeeld
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
let text = "";
for (const x in myObj) {
text += myObj[x] + ", ";
}