简体   繁体   中英

How do I access values of a JSON object extracted from quick.db?

I'm trying to access values from a JSON object, however, its formatting won't allow me to use the traditional methods of doing so. For example the formatting would be as follows:

{
  "123456789" : 0
  "12345678910" : 14
}

How would I be able to access the name and the value of the first field? ex. 123456789 and 14. I'ved tried to stringify the objects and just treat it as a regular string and finding the first instance of " and last instance of " to get the name and then finding the index of : and adding 1 to get the value. However, I don't think it would be efficient neither fully accurate. Is there a way to convert this JSON Object to a 2D Array? to access it more easily?

EDIT: I won't actually know the IDs stored in the JSON Object, they are randomly generated, which is why I've stated my previous solutions before and I won't be able to use traditional methods. So I need to find a way to grab the name and value without actually knowing them. Which is why storing a JSON object in a 2D array would be most useful but I need to know if it's possible

Using JSON.parse which parses a JSON string, constructing the JavaScript value or object described by the string passed to to it

In case you don't know the keys a head you can use the Object.keys method to get the object keys.

 const data = JSON.parse('{"123456789": 0, "12345678910": 14}'); console.log(data[12345678910]); console.log(data[123456789]); // in case you don't know the keys a head const keys = Object.keys(data); console.log(data[keys[0]]); console.log(data[keys[1]]);

More about JSON.parse in this link

It's fine to use JSON.parse() for example:

const xmlhttp = new XMLHttpRequest();
const url = "yourJsonFileName.json";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
    const myArr = JSON.parse(this.responseText);
document.write(myArr["12345678910"]) // => 14
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM