programing

레일에서 JSON 문자열을 JSON 어레이로 변환하시겠습니까?

telebox 2023. 3. 13. 20:22
반응형

레일에서 JSON 문자열을 JSON 어레이로 변환하시겠습니까?

아래와 같이 레일에 JSON 스트링이 있습니다.

[{"content":"1D","createdTime":"09-06-2011 00:59"},{"content":"2D","createdtime":"09-06-2011 08:00"}]

속성 콘텐츠 및 생성된 시간을 포함하는 클래스 콘텐츠의 객체입니다.

이 JSON 문자열을 각각의 JSON 오브젝트 배열로 변환하여 루프를 실행하고 JSON을 레일 내의 오브젝트로 디코딩합니다.어떻게 하면 좋을까요?

json 라이브러리 json을 사용할 수 있습니다.

다음 작업을 수행할 수 있습니다.

jsonArray = [{"content":"1D","createdTime":"09-06-2011 00:59"},   
              {"content":"2D","createdtime":"09-06-2011 08:00"}]
objArray = JSON.parse(jsonArray)

고객의 코멘트에 따라 JSON이 고객의 모델에 맞는 한 이 작업을 수행할 수 있습니다.

objArray.each do |object|
  # This is a hash object so now create a new one.
  newMyObject = MyObject.new(object)
  newMyObject.save # You can do validation or any other processing around here.
end

ActiveSupport::JSON.decode(string)서버측에서 맛있는 소모품으로 디코딩합니다.

JavaScript 코드가 내부일 경우 다음을 수행할 수 있습니다.

<script>
    var hives = <%=@hives.html_safe%>;
</script>

그렇지 않은 경우:

숨김 텍스트 영역과 set@hives.html_safe 값을 만듭니다.이것에 의해, 다음과 같이 JavaScript 로 요소의 값으로 취득할 수 있습니다.

html.erb 파일

<%= text_area_tag :hives_yearly_temp, @hives.html_safe, { style: "display: none;"} %>

js 파일 내

var hives = JSON.parse( $('#hives_yearly_temp').val() );

루프를 실행하려면

for(key in hives) {
  alert( hives[key] );
}

언급URL : https://stackoverflow.com/questions/6284743/convert-json-string-to-json-array-in-rails

반응형