programing

Javascript 개체를 Json 문자열로 인코딩하는 중

cafebook 2023. 3. 4. 15:10
반응형

Javascript 개체를 Json 문자열로 인코딩하는 중

Javascript 오브젝트를 JSON 문자열로 인코딩하고 싶은데 큰 어려움을 겪고 있습니다.

개체는 다음과 같습니다.

new_tweets[k]['tweet_id'] = 98745521;
new_tweets[k]['user_id'] = 54875;       
new_tweets[k]['data']['in_reply_to_screen_name'] = "other_user";
new_tweets[k]['data']['text'] = "tweet text";

이것을 JSON 문자열에 넣어 Ajax 요구에 넣고 싶다.

{'k':{'tweet_id':98745521,'user_id':54875, 'data':{...}}}

상황을 이해하게 될 거야내가 뭘 해도 소용없어.json2와 같은 모든 JSON 인코더 및 제품

[]

글쎄, 그건 도움이 안 돼요기본적으로는 php 같은 것을 갖고 싶습니다.encodejson기능.

변수가 없는 한k정의되어 있기 때문에 문제가 생겼을 겁니다.다음과 같은 방법으로 원하는 작업을 수행할 수 있습니다.

var new_tweets = { };

new_tweets.k = { };

new_tweets.k.tweet_id = 98745521;
new_tweets.k.user_id = 54875;

new_tweets.k.data = { };

new_tweets.k.data.in_reply_to_screen_name = 'other_user';
new_tweets.k.data.text = 'tweet text';

// Will create the JSON string you're looking for.
var json = JSON.stringify(new_tweets);

한 번에 모든 작업을 수행할 수도 있습니다.

var new_tweets = {
  k: {
    tweet_id: 98745521,
    user_id: 54875,
    data: {
      in_reply_to_screen_name: 'other_user',
      text: 'tweet_text'
    }
  }
}

다음과 같이 사용할 수 있습니다.

JSON.stringify(new_tweets);

언급URL : https://stackoverflow.com/questions/6810084/encoding-javascript-object-to-json-string

반응형