1

Here is my json array: Updated

    {
  "Title": "Limitless",
  "Year": "2011",
  "Rated": "PG-13",
  "Released": "2011-03-18",
  "Runtime": 105,

  "Actors": [
    "Bradley Cooper",
    "Robert De Niro",
    "Abbie Cornish",
    "Andrew Howard"
  ]

}

Here is my php return:

return response()->json($movie);

The Jquery:

$("#stars").val(data.Actors); //Nothing fancy about this. Just outputting data to an input field.

Result:

Bradley Cooper,Robert De Niro,Abbie Cornish,Andrew Howard

Why are there no spaces in between the names/comma's? Is there a way to achieve this without/with regex? Or is it a parsing error?

2
  • what is a "Json object array"?? How did you produce the first output, hence what is this in reality? Commented Aug 4, 2018 at 13:55
  • @Jeff I maybe confusing this too much. I have an array of json which is now updated above with a better readability. I am outputting that to a text field using jQuery (getting that via ajax call to my controller and the above jquery is used in my ajax success). But the problem is that the comma does not have spacing. Commented Aug 4, 2018 at 14:03

2 Answers 2

1

you should be writing it as

$("#stars").val(data.Actors.join(', '))
Sign up to request clarification or add additional context in comments.

9 Comments

Separator is not defined?
Updated the answer with seperator value.. i.e. ", "
So this is an array join correct? So we are saying, join the arrays with , comma and a space.
Yes exactly, $("#stars") is a textbox, and it can't simply show array.. so internally it's doing array.join with just comma... if you want comma with space, you need to do it like this..
So here is a thought. Now my data is dynamic. It may sometimes be an array. Sometimes its just one single json. So in that case, it is sure to throw an error correct? join is not a function. How would I resolve this?
|
0

You can try this... Implode with comma space.

Snippet

return response()->json(implode(', ', $movie->Actors));

We have imploded with , (comma + space)

4 Comments

It is a JSON Object. Hence will not work with str_replace
This is a good solution too. But I think I will go for the above solution. Thanks a bunch!
@BasicBud Yeah... This is server side(php) solution, and above is client side (jQuery).
Yes I am aware of that. Thanks mate :)

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.