0

Supposed that I have this JSON STRING that is stored in a vairable:

{"name":"Joene Floresca"},{"name":"Argel "}

How can I make it

["Joene", "Argel"]
4
  • 2
    Your JSON would be invalid without a [] around it to make it an array. Commented Jun 9, 2015 at 11:38
  • [{"name":"Joene Floresca"},{"name":"Argel "}] this is the correct way right?- @RGraham Commented Jun 9, 2015 at 11:39
  • you can use jQuery.parseJSON(); refer api.jquery.com/jquery.parsejson for further info. Commented Jun 9, 2015 at 11:40
  • 2
    @JoeneFloresca var jsonstring = '[{"name":"Joene Floresca"},{"name":"Argel "}]'; is json string. Commented Jun 9, 2015 at 11:41

3 Answers 3

1

You mention you have a string. Use JSON.parse for that. Also, make sure it is an array. Afterwards, you can manually iterate through each object in the array and push the value

var str = '[{"name": "Joene Floresca"},{ "name": "Argel "}]';
var objA = JSON.parse(str);
var values = [];

for (var i = 0; i < objA.length; i++) {
  for (var key in objA[i]) {
    values.push(objA[i][key]);
  }
}

console.log(values);

Sign up to request clarification or add additional context in comments.

Comments

1

Assuming your JSON is an array, you can use map:

// Your JSON string variable
var jsonString = '[{"name":"Joene Floresca"},{"name":"Argel "}]';
// Parse the JSON to a JS Object
var jsObject = $.parseJSON(jsonString);
// Use map to iterate the array
var arr = $.map(jsObject, function(element) {
    // Return the name element from each object
    return element.name;
});
console.log(arr); // Prints ["Joene Floresca", "Argel "]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments

0

You can iterate over objects inside array and store the names in a second array.

var data =  JSON.parse('[{"name":"Joene Floresca"},{"name":"Argel "}]');
var names = [];

data.forEach(function(model) {
  names.push(model.name);
});
// names now contains ["Joene Floresca", "Argel"]
alert(names);

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.