1

I'm just starting with JSON, and I have a beginners question.

I have JSON data in that form:

[{"price":"0"},{"price":"124"},{"price":"12"},{"price":"0"},{"price":"124"}]

Is it possible to change it, so the output will be [0,124,12,0,124]?

2
  • Depends on the language, but it's simply the JSON's values. Commented Apr 17, 2016 at 16:38
  • im working in javascript, how would i put just values in array? Commented Apr 17, 2016 at 16:39

6 Answers 6

2
var arr = [{"price":"0"},{"price":"124"},{"price":"12"},{"price":"0"},{"price":"124"}]

var arr2 = []

for (i in arr){ 
  arr2.push(arr[i].price)
}
Sign up to request clarification or add additional context in comments.

Comments

1

In jQuery you can use this function:

function objectArrayToValueString(objectArray) {

    var output = objectArray.map(function (each) {
        return parseInt(each.price);
    });

    return JSON.stringify(output);
}

var objectArray = [{ "price": "0" }, { "price": "124" }, { "price": "12" }, { "price": "0" }, { "price": "124" }];

var result = objectArrayToValueString(objectArray);

alert(result);

2 Comments

You are going round round for simple solution , can you explain why this much code is needed @HajkHovhannisyan
Because it's "platform independent" algorithm. But yes, you're right. Much cleaner solution in javascript is yours with JSON.stringify(output);
1
var array = [{"price":"0"},{"price":"124"},{"price":"12"},{"price":"0"},{"price":"124"}];

var output = array.map(function(each){
  return parseInt(each.price);
});

Comments

1

you can use map function,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

var temp = [{"price":"0"},{"price":"124"},{"price":"12"},{"price":"0"},{"price":"124"}];


 var arr = temp .map(function (el) {
      return el.price;
    });

console.log(arr)

Comments

1

You can use pasrseInt() function, which converts strings to integers, and JSON.parse(), which creates a javascript object from a json string.

So:

var s = '[{"price":"0"},{"price":"124"},{"price":"12"},{"price":"0"},{"price":"124"}]'
var list = JSON.parse(s)
var newArray = []
for (var i = 0; i < list.length; ++i) {
    var element = list[i]
    var obj = {}
    for (key in element) {
        obj[key] = parseInt(element[key])
    }
    newArray.push(obj)
}
s = JSON.stringify(newArray)

Comments

0

Just Loop through your array of JSON objects a replace that JSON object with value

var arr =[{"price":"0"},{"price":"124"},{"price":"12"},{"price":"0"},"price":"124"}];

for (i in arr){   
  arr[i]=parseInt(arr[i].price);  
}
console.log(arr);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.