简体   繁体   中英

Cannot reach Object/Json

i´m not sure what this is, but i belive it´s Json?
{"objekt_nr":"22133-01"}

I try to convert it into a string like this:

function myFunction(objNr){
    objNr = objNr.objekt_nr;
    console.log(objNr);

This will result in undefined .

If i comment the converting part, i get: {"objekt_nr":"22133-01"}

How can i get this Json / object / array in a string, like: 22133-01 ?

I´ve also tried: objNr = objNr[0]; and objNr = objNr['objekt_nr']

The code is working fine. Maybe the call of myFunction() is wrong.

The access of properties are:

  • direct object.property or
  • with a string object['property']

 var obj = { "objekt_nr": "22133-01" }; function myFunction(objNr) { objNr = objNr.objekt_nr; // i do not recommend the assignment to the former object! document.write(objNr); } myFunction(obj); 

Edit: Suppose you have a JSON string, like '{"objekt_nr":"22133-01"}' , then you have to parse it first with JSON.parse . The result is an object.

 function myFunction(JSONstring) { var obj = JSON.parse(JSONstring); document.write(obj.objekt_nr); } myFunction('{"objekt_nr": "22133-01"}'); 

You have a string of JSON which represents an object. You do not have an actual object (yet). If you want to access properties you need to first convert it to an object, using JSON.parse() :

var objNr = JSON.parse(objNr); // create an object from your JSON

function myFunction(objNr) {
    objNr = objNr.objekt_nr;
    console.log(objNr);
}

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