parse json object in javascript to get key and values

16,811

Solution 1

JSON.parse is use to parse JSONString to Javascript Object.

You can not use it directly on a JavaScript Object ...

Anyway, your object is an array so you may do :

var arr = JSON.parse(data);
arr.forEach(function(elementObject){
    var keys = Object.keys(elementObject);
    keys.forEach(function(key){
      console.log(key + ":"+elementObject[key]);
    })
});

Cheers

Solution 2

Here you will get the values in array "values".

var data= [{"obj1":"2122"},{"obj2":"123"}]
 
data = JSON.stringify(data);
 
var values = [];
 
JSON.parse(data, function (key, value) {

    if (typeof(value) != "object") {
        values.push({[key]:value});
	// values.push(value); //if you need a value array
    }  
});

Share:
16,811
Rajeshwar
Author by

Rajeshwar

Quick Learner,Javascript developer,PhP developer,Angular js,node js,mongo db

Updated on August 16, 2022

Comments

  • Rajeshwar
    Rajeshwar over 1 year

    I have a object, need to parse the below data

      var data= [{"obj1":"2122"},{"obj2":"123"}]
    

    to get both the keys and values in javascript. I yried to use:

    var obj = JSON.parse(data);
    for(var prop in data) {
    if(data.hasOwnProperty(prop))
      console.log(prop);
    }
    

    The values that are obtained in console are

    Object {obj1: "2122"}
    Object {obj2: "123"}
    

    But I need to access the values seperately and not as object. How to retrieve it from that object?

  • T J
    T J about 8 years
    "String to JSON" - no, it's for converting a JSON string (A string that adhere's to JavaScript Object Notation) to JavaScript object. JavaScript Object != JSON
  • mimiz
    mimiz about 8 years
    @Rajeshwar You're welcome, so please mark question as solved, T J you are right !
  • Alexander Higgins
    Alexander Higgins about 8 years
    Edit: Updated to answer question without changing data structure.