tomazj tomazj - 7 months ago 10
Javascript Question

How to convert JSON in other form?

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]
?

Answer

In jQuery you can use this function:

function jsonToArrayString(jsonString) {
  
  var jsArray = $.parseJSON(jsonString);
  var output = "[";

  $(jsArray).each(function(index, item) {

    if (index == 0) {
      output += item["price"];
    } else {
      output += "," + item["price"];
    }


  });

  output += "]";

  return output;
}

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

var result = jsonToArrayString(jsonString);

alert(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>