Using Number as "Index" (JSON)

Using number as index (JSON)

JSON only allows key names to be strings. Those strings can consist of numerical values.

You aren't using JSON though. You have a JavaScript object literal. You can use identifiers for keys, but an identifier can't start with a number. You can still use strings though.

var Game={
"status": [
{
"0": "val",
"1": "val",
"2": "val"
},
{
"0": "val",
"1": "val",
"2": "val"
}
]
}

If you access the properties with dot-notation, then you have to use identifiers. Use square bracket notation instead: Game.status[0][0].

But given that data, an array would seem to make more sense.

var Game={
"status": [
[
"val",
"val",
"val"
],
[
"val",
"val",
"val"
]
]
}

how to parse json based on index number of object

It is still an array so you wouldn't access it as a property with .[4] you would say to grab the X element of the actual array by saying data4[X].period

TLDR; replace data4.[1] with data4[1].period

let message = { payloadString: [{
"period": "202103092000",
"condition": "A mix of sun and cloud",
"temperature": "0",
"icon_code": "02",
"precip_probability": "0"
}, {
"period": "202103092100",
"condition": "Mainly sunny",
"temperature": "2",
"icon_code": "01",
"precip_probability": "0"
}, {
"period": "202103092200",
"condition": "Sunny",
"temperature": "2",
"icon_code": "00",
"precip_probability": "0"
}, {
"period": "202103092300",
"condition": "Sunny",
"temperature": "3",
"icon_code": "00",
"precip_probability": "0"
}]
}

var data4 = message.payloadString;
fcperiod2 = data4[1].period;
console.log(fcperiod2)

get json key and value by index instead of their names

You can transform the values into an array with Object.values, and then get the index you want:

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}')
console.log(obj.name) // John
var array = Object.values(obj)
console.log(array[0]) // John

Retrieving a property of a JSON object by index?

Objects in JavaScript are collections of unordered properties. Objects are hashtables.

If you want your properties to be in alphabetical order, one possible solution would be to create an index for your properties in a separate array. Just a few hours ago, I answered a question on Stack Overflow which you may want to check out:

  • Iterating over a JavaScript object in sort order based on particular key value of a child object

Here's a quick adaptation for your object1:

var obj = {
"set1": [1, 2, 3],
"set2": [4, 5, 6, 7, 8],
"set3": [9, 10, 11, 12]
};

var index = [];

// build the index
for (var x in obj) {
index.push(x);
}

// sort the index
index.sort(function (a, b) {
return a == b ? 0 : (a > b ? 1 : -1);
});

Then you would be able to do the following:

console.log(obj[index[1]]);

The answer I cited earlier proposes a reusable solution to iterate over such an object. That is unless you can change your JSON to as @Jacob Relkin suggested in the other answer, which could be easier.


1 You may want to use the hasOwnProperty() method to ensure that the properties belong to your object and are not inherited from Object.prototype.

How to get JSON values by index number using PostgerSQL?

If you need to deal with multiple keys/array elements, you can apply a limit clause when extracting the keys/elements.

select t.id, o.content
from test t
cross join lateral (
(
select content
from jsonb_each_text(t.name) as e(key,content)
where jsonb_typeof(t.name) = 'object'
limit 1
)
union all
(
select *
from jsonb_array_elements_text(t.name)
where jsonb_typeof(t.name) = 'array'
limit 1
)
) o ;

Note that the limit will pick an arbitrary element, it's not guaranteed that it's the "first" one - but highly likely.

To pick an element by index, you could use:

select t.id, o.content
from test t
cross join lateral (
select e.content
from jsonb_each_text(t.name) with ordinality as e(key,content,idx)
where jsonb_typeof(t.name) = 'object'
and e.idx = 1
union all
select e.element
from jsonb_array_elements_text(t.name) with ordinality as e(element,idx)
where jsonb_typeof(t.name) = 'array'
and e.idx = 1
) o ;

If your name column is defined as json (rather than jsonb which it should be), then you need to use the corresponding json_xxx function (not jsonb_xxx)

Online example

What is the best way of getting index from huge JSON Array of objects that matches with array of JSON objects

You can use Map Object for this.

let theMap = new Map(hugeArray.map((item, index) => [item.firstName + " " + item.lastName, index]));

let result = matchArray.map(item => theMap.get(item.firstName + " " + item.lastName))
.filter(i => i !== undefined)

This assumes firstName or lastName do not have spaces. Use another char if they might include spaces.

If hugeArray has duplicates:

let theMap = new Map();
hugeArray.forEach((item, index) => {
let key = item.firstName + " " + item.lastName;
let value = theMap.get(key);
if (value === undefined)
theMap.set(key, [index]);
else
value.push(index);
});

let result = matchArray.flatMap(item => theMap.get(item.firstName + " " + item.lastName))
.filter(i => i !== undefined);

If we need a sorted result when hugeArray has duplicates:

let result = matchArray.flatMap(item => theMap.get(item.firstName + " " + item.lastName))
.filter(i => i !== undefined).sort();

Find the highest number in a json object with javascript and a corresponding index or another value

Once you have the highest amount, you can .findIndex to get the object with that amount.

const shots=[{id:1,amount:2},{id:2,amount:4},{id:3,amount:52},{id:4,amount:36},{id:5,amount:13},{id:6,amount:33}];

const highest = Math.max(...shots.map(o => o.amount));
const index = shots.findIndex(o => o.amount === highest);
console.log(index, shots[index].id);

find index number of json element

No. The loop is just the way to go. However, if you need to do that search often on many elements, it might be efficient to build an index (or just deliver the JSON as an Array of numbers at once, if there are no other properties):

var indexArray = data.someList.map(function(o){return o.id;});
var currentidno = indexArray.indexOf(aid) + 1;

Or you could with indexing by object properties, instead of an array:

someValues = {"21154859":{index:0},"21154865":{index:1},"21154856":{index:2},"21154870":{index:3},... }; 
// no order needed!
var currentidno = someValues[aid].index + 1;

Get index position for a JSON item in Python

You can loop through all the members until you find the one you want:

data = json.load(jsonFile)
for member in data['members']:
if member['username'] == 'John Doe#0001':
member['posessions'].append(something)

Python: How to set a value from JSON as the index in a list?

Assuming you have a list of dicts you could do something like this:

json_lst = [{
"1234": "hello world"
},
{
"5678": "roses are red"
}]

result = {int(k) : v for element in json_lst for k, v in element.items()}
print(result[1234])

Output

hello world

The above dictionary comprehension is equivalent to the following nested loops:

result = {}
for element in json_lst:
for k, v in element.items():
result[int(k)] = v


Related Topics



Leave a reply



Submit