Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key value pairs using JSON

Is there a way to handle data structures using JSON object in a way of Key/ Value pairs?
If so can some one elaborate how to access associated value object from the key

Assume that I have something like this

KEY1 |  VALUE OBJECT1 - (NAME: "XXXXXX", VALUE:100.0)  
KEY2 |  VALUE OBJECT2 - (NAME: "YYYYYYY", VALUE:200.0)  
KEY3 |  VALUE OBJECT3 - (NAME: "ZZZZZZZ", VALUE:500.0)  
like image 804
SLM Avatar asked Sep 15 '10 07:09

SLM


People also ask

How does JSON create key-value pairs?

In order to set a key-value pair in a KiiObject, call the set() method of the KiiObject class. The set() method has an overloaded version for each data type. Specify a key-value pair as arguments of the set() method. The specified key-value pair will be saved at the first level of the JSON document hierarchy.

What is name-value pairs JSON?

JSON is basically a collection of name/value pairs, where the name will always be a string and values can be a string (in double quotes), a number, a boolean (true or false), null, an object, or an array. Each name-value pair will be separated by a comma.

Can a JSON key be a list?

JSONListKeys. Lists the object names (keys) or array indexes in JSON data for an element specified by an object name, an array index, or a path.

What are keys in JSON?

The two primary parts that make up JSON are keys and values. Together they make a key/value pair. Key: A key is always a string enclosed in quotation marks. Value: A value can be a string, number, boolean expression, array, or object.


1 Answers

A "JSON object" is actually an oxymoron. JSON is a text format describing an object, not an actual object, so data can either be in the form of JSON, or deserialised into an object.

The JSON for that would look like this:

{"KEY1":{"NAME":"XXXXXX","VALUE":100},"KEY2":{"NAME":"YYYYYYY","VALUE":200},"KEY3":{"NAME":"ZZZZZZZ","VALUE":500}}

Once you have parsed the JSON into a Javascript object (called data in the code below), you can for example access the object for KEY2 and it's properties like this:

var obj = data.KEY2;
alert(obj.NAME);
alert(obj.VALUE);

If you have the key as a string, you can use index notation:

var key = 'KEY3';
var obj = data[key];
like image 102
Guffa Avatar answered Sep 30 '22 02:09

Guffa