0

I have the following object that is structured as below in chrome network-> preview window:

n_days_orders: 
    index: ["Sun, 21 Oct 2018", "Mon, ...
    last_n: 7
    quantity: [0, 0, 0, 0, 0, 0, 0]

I am using the following to check if is a JSON object and if so parse it.

after How can I check if a value is a json object?

function isJSON (something) {
  if (typeof something !== 'string') {
    something = JSON.stringify(something)
  }
  try {
    JSON.parse(something)
    return true
  } catch (e) {
    return false
  }
}

if (isJSON(data.n_days_orders)) {
    try {
        daysOrders = JSON.parse(data.n_days_orders)
    } catch (e) {
        console.log(e.message)
        //the line below is printed
        >>Unexpected token o in JSON at position 1
    }
}

How can I get the value in the object without throwing an error?

proximacentauri
  • 1,749
  • 5
  • 25
  • 53
  • What is the problem? you did not say what exactly is it you are after and why the current way doesn't work for you – vsync Oct 28 '18 at 14:13
  • 1
    You need to parse `data` first. A string will not have properties like `n_days_orders` until you convert it to an object – charlietfl Oct 28 '18 at 14:17
  • 1
    That error usually means that the data is already an object, not a JSON string, so there's no need to call `JSON.parse` on it. – Daniel Beck Oct 28 '18 at 14:17
  • 1
    [There is no such thing as a "JSON Object"](https://stackoverflow.com/questions/2904131/what-is-the-difference-between-json-and-object-literal-notation). `isJSON({})` evaluates to true but `{}` is not JSON at all. – str Oct 28 '18 at 14:19
  • 1
    (Remember JSON is a *string* that can be converted into an object; it is not the object itself. Assuming you're getting this data via a jQuery AJAX request, it's probably already done the conversion for you before this code runs; it does this automatically based on the response MIME type or the dataType declared in the call.) – Daniel Beck Oct 28 '18 at 14:30

1 Answers1

1

Try isJSON as a parser to detect and try parse the value or throw an error. A way to access obj property without having problems with its existence on a reference is by the index value

let t = data.n_days_orders //will raise an exception if the field does not exist;
let tmp = data['n_days_orders'] //will allow you the cast and return an undefined value

A proper way to check a string if it is a valid JSON is to try to parse it and handle an exception. js typeof comparison will return 'object'.

If you are willing to create a prototype or a checker of a JSON format described by a model, a way is to check its fields in a loop and check their existence but this will cost you an O(props) notation for each object so care for delays.

function checkMyModel(model , prototypemodel){
    let props = Object.keys(prototypemodel);
    let notexist = props.filter((p)=>{
        return (model[p] === undefined );
    })
    console.log(notexist);
    return notexist.length > 0 ? false : true;
}
var proto = {id: null, name:null , value:null , z : null }
var m1 = {id: 1, name:'john' , z : null }
var m2 = {id: 1, name:'john1' ,value:'iam a value2'}
var m3 = {id: 1, name:'john2' ,value:'iam a value3' , z : 34 }

console.log(checkMyModel(m1,proto)); //false missing value
console.log(checkMyModel(m2,proto)); //false missing z

But I suppose you want to check only if the property exists

function isJSON (something) {
  try {
      return(typeof something !== 'object') ? JSON.parse(something) : something;
  } catch (e){ console.warn(e);throw e; }
}
function getDayOrdes (value){
  try {
        let obj = isJSON(value);
        let t= obj['n_days_orders'] ;
        return  (t !== null && t !== undefined) ? t : [];
  } catch (e) { return e.message; }
}

var obj1 = { id : 'order1' , value : '111$'}, obj2 = { id : 'order2' , value : '222$'};
var json1 = { id: '' , n_days_orders: [obj1 , obj2]};
var json2 = JSON.stringify(json1) ,json3 = { id: 1 , values: [obj1 , obj2]};

console.log(getDayOrdes(json1)); //returns obj
console.log(getDayOrdes(json2 + 'zasaza')); //throws json parse error
console.log(getDayOrdes(json2)); //returns obj
console.log(getDayOrdes(json3)); //undefined n_days_orders does not exist