繁体   English   中英

我正在尝试从 Node.JS 中的 JSON 获取值

[英]I am trying to get Values from JSON in Node.JS

我正在尝试从节点中的 json 获取值。

这是代码:

    https.get('https://www.reddit.com/r/cute/random.json', (resp) => {
    let data = '';

    resp.on('data', (chunk) => {
        data += chunk;
    });

    const obj = JSON.parse(data);
    resp.on('end', () => {
        console.log(obj.url);
    });

    }).on("error", (err) => {
    console.log("Error: " + err.message);
    });

首先我从 Reddit 获取 json 文件,然后代码应该解析数据,获取 url 值并打印。

这是reddit的回复:

[{"kind": "Listing", "data": {"modhash": "k08cakl21qf62e475cdf685ff8f62982c15997278420b30b86", "dist": 1, "children": [{"kind": "t3", "data": {"approved_at_utc": null, "subreddit": "cute", "selftext": "", "user_reports": [], "saved": false, "mod_reason_title": null, "gilded": 0, "clicked": false, "title": "Took this picture at my local zoo", "link_flair_richtext": [], "subreddit_name_prefixed": "r/cute", "hidden": false, "pwls": 6, "link_flair_css_class": null, "downs": 0, "thumbnail_height": 140, "top_awarded_type": null, "parent_whitelist_status": "all_ads", "hide_score": false, "name": "t3_np1ulg", "quarantine": false, "link_flair_text_color": "dark", "upvote_ratio": 1.0, "author_flair_background_color": null, "subreddit_type": "public", "ups": 13, "total_awards_received": 0, "media_embed": {}, "thumbnail_width": 140, "author_flair_template_id": null, "is_original_content": false, "author_fullname": "t2_6oq8e4ri", "secure_media": null, "is_reddit_media_domain": true, "is_meta": false, "category": null, "secure_media_embed": {}, "link_flair_text": null, "can_mod_post": false, "score": 13, "approved_by": null, "is_created_from_ads_ui": false, "author_premium": false, "thumbnail": "https://b.thumbs.redditmedia.com/rcVqy9jgOCmApJ36YpAN9CCDQ2lRC0hSsAqBpt0zBxw.jpg", "edited": false, "author_flair_css_class": null, "author_flair_richtext": [], "gildings": {}, "post_hint": "image", "content_categories": null, "is_self": false, "mod_note": null, "created": 1622491454.0, "link_flair_type": "text", "wls": 6, "removed_by_category": null, "banned_by": null, "author_flair_type": "text", "domain": "i.redd.it", "allow_live_comments": false, "selftext_html": null, "likes": null, "suggested_sort": null, "banned_at_utc": null, "url_overridden_by_dest": "https://i.redd.it/h9b00p6y4g271.jpg", "view_count": null, "archived": false, "no_follow": false, "is_crosspostable": true, "pinned": false, "over_18": false, "preview": {"images": [{"source": {"url": "https://preview.redd.it/h9b00p6y4g271.jpg?auto=webp&s=9962d8aa05efc905e39b67bff7a3385576ef4267", "width": 2448, "height": 3264}, "resolutions": [{"url": "https://preview.redd.it/h9b00p6y4g271.jpg?width=108&crop=smart&auto=webp&s=a30f747ccc3a51648498dbe90ffc92f114f438e5", "width": 108, "height": 144}, {"url": "https://preview.redd.it/h9b00p6y4g271.jpg?width=216&crop=smart&auto=webp&s=4bade02391aff8db706eeb74c3354aace0195048", "width": 216, "height": 288}, {"url": "https://preview.redd.it/h9b00p6y4g271.jpg?width=320&crop=smart&auto=webp&s=76bec250dec57f8ee75c379188c2d209eaa21646", "width": 320, "height": 426}, {"url": "https://preview.redd.it/h9b00p6y4g271.jpg?width=640&crop=smart&auto=webp&s=520ab610461f06a6d64f3a183ef25e33cdee4625", "width": 640, "height": 853}, {"url": "https://preview.redd.it/h9b00p6y4g271.jpg?width=960&crop=smart&auto=webp&s=961c512920a728777b9b13185d53f9afe4f6aaea", "width": 960, "height": 1280}, {"url": "https://preview.redd.it/h9b00p6y4g271.jpg?width=1080&crop=smart&auto=webp&s=6f943fbd5d53b892dd15b28052f12c929e5887b9", "width": 1080, "height": 1440}], "variants": {}, "id": "W08V856IQ3icquk8jx2Q0UiWHZnlDFcsSY7Cdu8J-S4"}], "enabled": true}, "all_awardings": [], "awarders": [], "media_only": false, "can_gild": true, "spoiler": false, "locked": false, "author_flair_text": null, "treatment_tags": [], "visited": false, "removed_by": null, "num_reports": null, "distinguished": null, "subreddit_id": "t5_2qh5l", "mod_reason_by": null, "removal_reason": null, "link_flair_background_color": "", "id": "np1ulg", "is_robot_indexable": true, "num_duplicates": 0, "report_reasons": null, "author": "ForMotherRussia3", "discussion_type": null, "num_comments": 1, "send_replies": true, "media": null, "contest_mode": false, "author_patreon_flair": false, "author_flair_text_color": null, "permalink": "/r/cute/comments/np1ulg/took_this_picture_at_my_local_zoo/", "whitelist_status": "all_ads", "stickied": false, "url": "https://i.redd.it/h9b00p6y4g271.jpg", "subreddit_subscribers": 96358, "created_utc": 1622462654.0, "num_crossposts": 0, "mod_reports": [], "is_video": false}}], "after": null, "before": null}}, {"kind": "Listing", "data": {"modhash": "k08cakl21qf62e475cdf685ff8f62982c15997278420b30b86", "dist": null, "children": [{"kind": "t1", "data": {"total_awards_received": 0, "approved_at_utc": null, "comment_type": null, "awarders": [], "mod_reason_by": null, "banned_by": null, "ups": 1, "author_flair_type": "text", "removal_reason": null, "link_id": "t3_np1ulg", "author_flair_template_id": null, "likes": null, "replies": "", "user_reports": [], "saved": false, "id": "h02og3g", "banned_at_utc": null, "mod_reason_title": null, "gilded": 0, "archived": false, "no_follow": true, "author": "AutoModerator", "can_mod_post": false, "send_replies": false, "parent_id": "t3_np1ulg", "score": 1, "author_fullname": "t2_6l4z3", "report_reasons": null, "approved_by": null, "all_awardings": [], "subreddit_id": "t5_2qh5l", "body": "This is the perfect post for r/cute!\n\n*I am a bot, and this action was performed automatically. Please [contact the moderators of this subreddit](/message/compose/?to=/r/cute) if you have any questions or concerns.*", "edited": false, "downs": 0, "author_flair_css_class": null, "is_submitter": false, "collapsed": false, "author_flair_richtext": [], "author_patreon_flair": false, "body_html": "<div class=\"md\"><p>This is the perfect post for <a href=\"/r/cute\">r/cute</a>!</p>\n\n<p><em>I am a bot, and this action was performed automatically. Please <a href=\"/message/compose/?to=/r/cute\">contact the moderators of this subreddit</a> if you have any questions or concerns.</em></p>\n</div>", "gildings": {}, "collapsed_reason": null, "associated_award": null, "stickied": false, "author_premium": true, "subreddit_type": "public", "can_gild": true, "top_awarded_type": null, "author_flair_text_color": null, "score_hidden": false, "permalink": "/r/cute/comments/np1ulg/took_this_picture_at_my_local_zoo/h02og3g/", "num_reports": null, "locked": false, "name": "t1_h02og3g", "created": 1622491455.0, "subreddit": "cute", "author_flair_text": null, "treatment_tags": [], "created_utc": 1622462655.0, "subreddit_name_prefixed": "r/cute", "controversiality": 0, "depth": 0, "author_flair_background_color": null, "collapsed_because_crowd_control": null, "mod_reports": [], "mod_note": null, "distinguished": "moderator"}}], "after": null, "before": null}}]

当我运行代码时(包含存在但未显示在我已导入 https 的代码片段中)我收到此错误:

SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at ClientRequest.<anonymous> (C:\Users\cameron\Desktop\cjp\bot.js:22:20)
at Object.onceWrapper (node:events:485:26)
at ClientRequest.emit (node:events:378:20)
at HTTPParser.parserOnIncomingClient [as onIncoming] (node:_http_client:636:27)
at HTTPParser.parserOnHeadersComplete (node:_http_common:129:17)
at TLSSocket.socketOnData (node:_http_client:502:22)
at TLSSocket.emit (node:events:378:20)
at addChunk (node:internal/streams/readable:313:12)
at readableAddChunk (node:internal/streams/readable:288:9)

提前感谢您的帮助!

此处更新代码:

const fetch = require("node-fetch");
const main = async () => {
  const json = await fetch("https://www.reddit.com/r/cute/random.json").then(
    res => res.json()
  );
  console.log(
    json
      .map(entry => entry.data.children.map(child => child.data.url))
      .flat()
      .filter(Boolean)
  );
};
main();

我正在遍历数据并获取列表的 output,我猜只有一个 URL 填充了k3类型。 所以你在这里得到一个 output :

运行#1

[ 'https://i.redd.it/pjom447yp8271.jpg' ]

运行#2

[ 'https://i.redd.it/h9b00p6y4g271.jpg' ]

运行#3

[ 'https://v.redd.it/lcejh8z6zp271' ]

上一个答案供您参考:

简单来说,你可以使用类似node-fetch东西:

const fetch = require("node-fetch");
const main = async () => {
  const json = await fetch("https://www.reddit.com/r/cute/random.json").then(
    res => res.json()
  );
  console.log(json);
};
main();

您将在console.log()中获得内容。 当我使用 Node JS 运行它时,我得到 output so.js

$ node so   
[
  {
    kind: 'Listing',
    data: {
      modhash: '',
      dist: 1,
      children: [Array],
      after: null,
      before: null
    }
  },
  {
    kind: 'Listing',
    data: {
      modhash: '',
      dist: null,
      children: [Array],
      after: null,
      before: null
    }
  }
]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM