user3272483
user3272483

Reputation: 408

Stringify and parse an object literal

I have this object literal

var rides = {
  brand: {
    type: String,
    label: "搜尋",
    max: 100
  },
  model: {
    type: String,
    label: "Tìm kiếm",
    max: 100
  },
  fueltype: {
    type: String,
    label: "Пошук",
    allowedValues: ['Petrol', 'Diesel', 'Hybrid', 'Electric'],
  },
  bodystyle: {
    type: String,
    label: "بحث",
    allowedValues: ['Convertibles', 'Coupes', 'Hatchbacks', 'Vans', 'Sedans', 'Suvs', 'Trucks', 'Wagons'],
    optional: true
  },
  topspeed: {
    type: Number,
    label: "חיפוש",
    optional: true
  },
  power: {
    type: Number,
    label: "Power (HP)",
    optional: true
  }
};

which i have stringfied in this way

var ss = JSON.stringify(rides);

However, for what I am doing to work, I need to get the object i stringfied exactly the way it was before i stringfied

Thi is what it looks like https://jsfiddle.net/y37crsvd/1/

Object { brand: Object, model: Object, fueltype: Object, bodystyle: Object, topspeed: Object, power: Object }

How can I stringify the object literal so as to show the nested object properties?

Upvotes: 0

Views: 223

Answers (3)

dandavis
dandavis

Reputation: 16726

You can't stringify() functions, unless you use a custom revive parameter on JSON.parse(), and a custom mapper parameter on JSON.stringify(). Or, define Function.prototype.toJSON to get the "plain" JSON.stringify() to work with functions like window.Number and window.String.

Upvotes: 1

BrunoLM
BrunoLM

Reputation: 100331

When you log xx the console shows the object and allow you to expand the properties. It also puts the properties in alphabetic order.

If you do a JSON.stringify(xx) you will see exactly the same string as you input in the first time (properties in the same order...).

Upvotes: 1

Lucero
Lucero

Reputation: 60190

The xx in the fiddle does contain the nested object properties, it's the console which requires you to expand the inner properties as well...

Upvotes: 1

Related Questions