为什么JS无法识别嵌套JSON中的json变量。

huangapple go评论87阅读模式
英文:

Why is JS not recognizing the json variable in nested json

问题

以下是代码部分的翻译:

  1. 我正在尝试在HTML中使用JavaScript设置动态个人资料卡并使用外部JSON文件我一直遇到一个问题JS JSON脚本的社交部分显示值为未定义
  2. <script>
  3. var profiles = {}
  4. window.onload = function () {
  5. GetProfiles()
  6. }
  7. function GetProfiles(){
  8. $.getJSON('https://gameremporium.us/image/Profile/profile.json', function(data) {
  9. var projson = data;
  10. for(var q in projson){
  11. jsonpro = projson[q];
  12. for(var i in jsonpro){
  13. profile = jsonpro[i];
  14. if (typeof profile["name"] != "" || typeof profile["name"] != undefined){
  15. profiles["name"] += profile.name;
  16. }
  17. if (typeof profile["Nick_name"] != "" || typeof profile["Nick_name"] != undefined){
  18. profiles["Nick"] += profile.Nick_name;
  19. }
  20. if (typeof profile["role"] != "" || typeof profile["role"] != undefined){
  21. profiles["role"] += profile.role;
  22. }
  23. if (typeof profile["description"] != "" || typeof profile["description"] != undefined){
  24. profiles["description"] += profile.description;
  25. }
  26. if (typeof profile["image"] != "" || typeof profile["image"] != undefined){
  27. profiles["image"] += profile.image_name;
  28. }
  29. if (typeof profile["imageBG"] != "" || typeof profile["imageBG"] != undefined){
  30. profiles["imageBG"] += profile.imageBG_name;
  31. }
  32. if (typeof profile["contact"] != "" || typeof profile["contact"] != undefined){
  33. profiles["contact"] += profile.contact_link;
  34. }
  35. for(var a in profile){
  36. social = profile[a].social_links;
  37. for(var a in social){
  38. media = social[a]
  39. if(media["link_one"].name && media["link_one"].link != ""){
  40. profiles.social["link_one"]["name"] += media.name;
  41. profiles.social["link_one"]["link"] += media.link;
  42. }
  43. if(media.name && media.link != ""){
  44. profiles.social["link_two"]["name"] += media.name
  45. profiles.social["link_two"]["link"] += media.link
  46. }
  47. if(media.name && media.link != ""){
  48. profiles.social["link_three"]["name"] += media.name
  49. profiles.social["link_three"]["link"] += media.link
  50. }
  51. if(media.name && media.link_four.link != ""){
  52. profiles.social["link_four"]["name"] += media.name
  53. profiles.social["link_four"]["link"] += media.link
  54. }
  55. if(media.name && media.link != ""){
  56. profiles.social["link_five"]["name"] += media.name
  57. profiles.social["link_five"]["link"] += media.link
  58. }
  59. if(media.name && media.link != ""){
  60. profiles.social["link_six"]["name"] += media.name
  61. profiles.social["link_six"]["link"] += media.link
  62. }
  63. }
  64. }
  65. SetProfiles(profiles);
  66. }
  67. };
  68. })
  69. };
  70. function SetProfiles(profiles){
  71. for(var i in profiles){
  72. profile = profiles[i];
  73. document.getElementById("profiles").innerHTML = '<div class="card"><img src="'+profile["imageBG"]+'" alt="background-image" class="bg-img"><img src="'+profile["image"]+'" alt="avatar" class="profile-img"><h1>"'+profile["name"]+'"</h1><p class="about-info">"'+profile["description"]+'"</p><a href="'+profile["contact"]+'" class="btn">Contact</a><ul class="social-list" id="social"><li><a href="@" class="social-link"><i class="fa fa-facebook-square"></i></a></li></ul></div>';
  74. }
  75. }</script>

对于代码中的问题,你提到社交部分的名字值无法获得,但这个问题可能需要更多的上下文和调试信息来确定。如果你需要更多帮助,可以提供更多细节,以便我可以帮助你更好地解决这个问题。

英文:

I was working on setting dynamic profile cards for html in js and using an external json file and i keep running into a problem where the socials part of the js json script displays the values as undefined

  1. &lt;script&gt;var profiles = {}
  2. window.onload = function () {
  3. GetProfiles()
  4. }
  5. function GetProfiles(){
  6. $.getJSON(&#39;https://gameremporium.us/image/Profile/profile.json&#39;, function(data) {
  7. var projson = data;
  8. for(var q in projson){
  9. jsonpro = projson[q];
  10. for(var i in jsonpro){
  11. profile = jsonpro[i];
  12. if (typeof profile[&quot;name&quot;] != &quot;&quot; || typeof profile[&quot;name&quot;] != undefined){
  13. profiles[&quot;name&quot;] += profile.name;
  14. }
  15. if (typeof profile[&quot;Nick_name&quot;] != &quot;&quot; || typeof profile[&quot;Nick_name&quot;] != undefined){
  16. profiles[&quot;Nick&quot;] += profile.Nick_name;
  17. }
  18. if (typeof profile[&quot;role&quot;] != &quot;&quot; || typeof profile[&quot;role&quot;] != undefined){
  19. profiles[&quot;role&quot;] += profile.role;
  20. }
  21. if (typeof profile[&quot;description&quot;] != &quot;&quot; || typeof profile[&quot;description&quot;] != undefined){
  22. profiles[&quot;description&quot;] += profile.description;
  23. }
  24. if (typeof profile[&quot;image&quot;] != &quot;&quot; || typeof profile[&quot;image&quot;] != undefined){
  25. profiles[&quot;image&quot;] += profile.image_name;
  26. }
  27. if (typeof profile[&quot;imageBG&quot;] != &quot;&quot; || typeof profile[&quot;imageBG&quot;] != undefined){
  28. profiles[&quot;imageBG&quot;] += profile.imageBG_name;
  29. }
  30. if (typeof profile[&quot;contact&quot;] != &quot;&quot; || typeof profile[&quot;contact&quot;] != undefined){
  31. profiles[&quot;contact&quot;] += profile.contact_link;
  32. }
  33. for(var a in profile){
  34. social = profile[a].social_links;
  35. for(var a in social){
  36. media = social[a]
  37. if(media[&quot;link_one&quot;].name &amp;&amp; media[&quot;link_one&quot;].link != &quot;&quot;){
  38. profiles.social[&quot;link_one&quot;][&quot;name&quot;] += media.name;
  39. profiles.social[&quot;link_one&quot;][&quot;link&quot;] += media.link;
  40. }
  41. if(media.name &amp;&amp; media.link != &quot;&quot;){
  42. profiles.social[&quot;link_two&quot;][&quot;name&quot;] += media.name
  43. profiles.social[&quot;link_two&quot;][&quot;link&quot;] += media.link
  44. }
  45. if(media.name &amp;&amp; media.link != &quot;&quot;){
  46. profiles.social[&quot;link_three&quot;][&quot;name&quot;] += media.name
  47. profiles.social[&quot;link_three&quot;][&quot;link&quot;] += media.link
  48. }
  49. if(media.name &amp;&amp; media.link_four.link != &quot;&quot;){
  50. profiles.social[&quot;link_four&quot;][&quot;name&quot;] += media.name
  51. profiles.social[&quot;link_four&quot;][&quot;link&quot;] += media.link
  52. }
  53. if(media.name &amp;&amp; media.link != &quot;&quot;){
  54. profiles.social[&quot;link_five&quot;][&quot;name&quot;] += media.name
  55. profiles.social[&quot;link_five&quot;][&quot;link&quot;] += media.link
  56. }
  57. if(media.name &amp;&amp; media.link != &quot;&quot;){
  58. profiles.social[&quot;link_six&quot;][&quot;name&quot;] += media.name
  59. profiles.social[&quot;link_six&quot;][&quot;link&quot;] += media.link
  60. }
  61. }
  62. }
  63. SetProfiles(profiles);
  64. }
  65. };
  66. })
  67. };
  68. function SetProfiles(profiles){
  69. for(var i in profiles){
  70. profile = profiles[i];
  71. document.getElementById(&quot;profiles&quot;).innerHTML = &#39;&lt;div class=&quot;card&quot;&gt;&lt;img src=&quot;&#39;+profile[&quot;imageBG&quot;]+&#39;&quot; alt=&quot;background-image&quot; class=&quot;bg-img&quot;&gt;&lt;img src=&#39;+profile[&quot;image&quot;]+&#39;&quot; alt=&quot;avatar&quot; class=&quot;profile-img&quot;&gt;&lt;h1&gt;&quot;&#39;+profile[&quot;name&quot;]+&#39;&quot;&lt;/h1&gt;&lt;p class=&quot;about-info&quot;&gt;&quot;&#39;+profile[&quot;description&quot;]+&#39;&quot;&lt;/p&gt;&lt;a href=&quot;&#39;+profile[&quot;contact&quot;]+&#39;&quot; class=&quot;btn&quot;&gt;Contact&lt;/a&gt;&lt;ul class=&quot;social-list&quot; id=&quot;social&quot;&gt;&lt;li&gt;&lt;a href=&quot;@&quot; class=&quot;social-link&quot;&gt;&lt;i class=&quot;fa fa-facebook-square&quot;&gt;&lt;/i&gt;&lt;/a&gt;&lt;/li&gt;&lt;/ul&gt;&lt;/div&gt;&#39;;
  72. }
  73. }&lt;/script&gt;
  74. THe problem

code is below and is not getting the name value from the socials nested value in the profiles part of the json file

  1. for(var a in profile){
  2. social += profile[a].social_links;
  3. if(typeof social.link_one.name &amp;&amp; social.social_links.link_one.link != &quot;&quot;){

EDIT: Updated the code now just displays everything back to the underfined

答案1

得分: 0

这是代码的翻译部分:

  1. There's too much to fix in your example code so instead of going over it line by line I'll just provide this alternative code suggestion.
  2. <!-- begin snippet: js hide: false console: true babel: false -->
  3. <!-- language: lang-js -->
  4. // kicks off the profile fetching/rendering
  5. makeCards();
  6. // gets the data and invokes addCard for each profile
  7. async function makeCards () {
  8. const json = await getProfiles();
  9. const container = document.getElementById('profiles');
  10. Object.values(json.Profiles).forEach(profile => addCard(profile, container));
  11. }
  12. // makes an individual profile card and adds to parent
  13. function addCard(profile, parent) {
  14. // bail if we don't have a profile or a parent node
  15. if (!profile || !parent) {
  16. return;
  17. }
  18. // use a template literal instead of string concatenation for the html
  19. parent.innerHTML += `
  20. <div class="card">
  21. ${imgHtml(profile)}
  22. <h1>${profile.name}</h1>
  23. <p class="about-info">
  24. ${contactLinkHtml(profile)}
  25. <ul class="social-list" id="social">
  26. <li>
  27. <a href="@link" class="social-link"><i class="fa facebook-square"></i></a>
  28. </li>
  29. </ul>
  30. </p>
  31. </div>
  32. `
  33. }
  34. // use fallback image when image_name isn't present
  35. function imgHtml ({image_name}) {
  36. return `<img src="${image_name || '//placekitten.com/200'}" alt="avatar" class="profile-img" />`
  37. }
  38. // return html only when contact_link is present
  39. function contactLinkHtml ({contact_link}) {
  40. return !contact_link ? '' : `<a href="${contact_link}" class="btn">Contact</a>`
  41. }
  42. // ------ the rest is just hand-waving data stuff --------- //
  43. // simulate the fetch request
  44. async function getProfiles() {
  45. return new Promise((resolve) => {
  46. setTimeout(resolve(json(), 500));
  47. })
  48. }
  49. // sample data
  50. function json() {
  51. return {
  52. "Profiles": {
  53. "profile 1": {
  54. "name": "LoneOxi",
  55. "Nick_name": "",
  56. "image_name": "",
  57. "imageBG_name": "",
  58. "contact_link": "",
  59. "description": "",
  60. "role": "",
  61. "social_links": {
  62. "link_one": {
  63. "name": "",
  64. "link": ""
  65. },
  66. "link_two": {
  67. "name": "",
  68. "link": ""
  69. },
  70. "link_three": {
  71. "name": "",
  72. "link": ""
  73. },
  74. "link_four": {
  75. "name": "",
  76. "link": ""
  77. },
  78. "link_five": {
  79. "name": "",
  80. "link": ""
  81. },
  82. "link_six": {
  83. "name": "",
  84. "link": ""
  85. },
  86. "link_seven": {
  87. "name": "",
  88. "link": ""
  89. }
  90. }
  91. },
  92. "profile 2": {
  93. "name": "Lonnie Gibson",
  94. "Nick_name": "Quentin",
  95. "image_name": "//placekitten.com/201",
  96. "imageBG_name": "LonnieGBG.jpg",
  97. "contact_link": "",
  98. "description": "",
  99. "role": "",
  100. "social_links": {
  101. "link_one": {
  102. "name": "",
  103. "link": ""
  104. },
  105. "link_two": {
  106. "name": "",
  107. "link": ""
  108. },
  109. "link_three": {
  110. "name": "",
  111. "link": ""
  112. },
  113. "link_four": {
  114. "name": "",
  115. "link": ""
  116. },
  117. "link_five": {
  118. "name": "",
  119. "link": ""
  120. },
  121. "link_six": {
  122. "name": "",
  123. "link": ""
  124. },
  125. "link_seven": {
  126. "name": "",
  127. "link": ""
  128. }
  129. }
  130. }
  131. }
  132. }
  133. }
  134. <!-- language: lang-css -->
  135. :root {
  136. font-family: sans-serif;
  137. }
  138. ul {
  139. list-style: none;
  140. margin: 0;
  141. padding: 0;
  142. }
  143. #profiles {
  144. display: flex;
  145. flex-wrap: wrap;
  146. gap: 1rem;
  147. }
  148. .card {
  149. border-radius: 8px;
  150. box-shadow: 4px 4px 8px #00000033;
  151. width: 200px;
  152. padding: .5rem;
  153. }
  154. .profile-img {
  155. width: 100px;
  156. aspect-ratio: 1;
  157. border-radius: 4px;
  158. }
  159. <!-- language: lang-html -->
  160. <div id="profiles"></div>
  161. <!-- end snippet -->

希望这有帮助!如果你需要进一步的翻译,请告诉我。

英文:

There's too much to fix in your example code so instead of going over it line by line I'll just provide this alternative code suggestion.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

  1. // kicks off the profile fetching/rendering
  2. makeCards();
  3. // gets the data and invokes addCard for each profile
  4. async function makeCards () {
  5. const json = await getProfiles();
  6. const container = document.getElementById(&#39;profiles&#39;);
  7. Object.values(json.Profiles).forEach(profile =&gt; addCard(profile, container));
  8. }
  9. // makes an individual profile card and adds to parent
  10. function addCard(profile, parent) {
  11. // bail if we don&#39;t have a profile or a parent node
  12. if (!profile || !parent) {
  13. return;
  14. }
  15. // use a template literal instead of string concatenation for the html
  16. parent.innerHTML += `
  17. &lt;div class=&quot;card&quot;&gt;
  18. ${imgHtml(profile)}
  19. &lt;h1&gt;${profile.name}&lt;/h1&gt;
  20. &lt;p class=&quot;about-info&quot;&gt;
  21. ${contactLinkHtml(profile)}
  22. &lt;ul class=&quot;social-list&quot; id=&quot;social&quot;&gt;
  23. &lt;li&gt;
  24. &lt;a href=&quot;@&quot; class=&quot;social-link&gt;&lt;i class=&quot;fa facebook-square&quot;&gt;&lt;/i&gt;&lt;/a&gt;
  25. &lt;/li&gt;
  26. &lt;/ul&gt;
  27. &lt;/p&gt;
  28. &lt;/div&gt;
  29. `
  30. }
  31. // use fallback image when image_name isn&#39;t present
  32. function imgHtml ({image_name}) {
  33. return `&lt;img src=&quot;${image_name || &#39;//placekitten.com/200&#39;}&quot; alt=&quot;avatar&quot; class=&quot;profile-img&quot; /&gt;`
  34. }
  35. // return html only when contact_link is present
  36. function contactLinkHtml ({contact_link}) {
  37. return !contact_link ? &#39;&#39; : `&lt;a href=&quot;${contact_link}&quot; class=&quot;btn&quot;&gt;Contact&lt;/a&gt;`
  38. }

// ------ the rest is just hand-waving data stuff --------- //

  1. // simulate the fetch request
  2. async function getProfiles() {
  3. return new Promise((resolve) =&gt; {
  4. setTimeout(resolve(json(), 500));
  5. })
  6. }
  7. // sample data
  8. function json() {
  9. return {
  10. &quot;Profiles&quot;: {
  11. &quot;profile 1&quot;: {
  12. &quot;name&quot;: &quot;LoneOxi&quot;,
  13. &quot;Nick_name&quot;: &quot;&quot;,
  14. &quot;image_name&quot;: &quot;&quot;,
  15. &quot;imageBG_name&quot;: &quot;&quot;,
  16. &quot;contact_link&quot;: &quot;&quot;,
  17. &quot;description&quot;: &quot;&quot;,
  18. &quot;role&quot;: &quot;&quot;,
  19. &quot;social_links&quot;: {
  20. &quot;link_one&quot;: {
  21. &quot;name&quot;: &quot;&quot;,
  22. &quot;link&quot;: &quot;&quot;
  23. },
  24. &quot;link_two&quot;: {
  25. &quot;name&quot;: &quot;&quot;,
  26. &quot;link&quot;: &quot;&quot;
  27. },
  28. &quot;link_three&quot;: {
  29. &quot;name&quot;: &quot;&quot;,
  30. &quot;link&quot;: &quot;&quot;
  31. },
  32. &quot;link_four&quot;: {
  33. &quot;name&quot;: &quot;&quot;,
  34. &quot;link&quot;: &quot;&quot;
  35. },
  36. &quot;link_five&quot;: {
  37. &quot;name&quot;: &quot;&quot;,
  38. &quot;link&quot;: &quot;&quot;
  39. },
  40. &quot;link_six&quot;: {
  41. &quot;name&quot;: &quot;&quot;,
  42. &quot;link&quot;: &quot;&quot;
  43. },
  44. &quot;link_seven&quot;: {
  45. &quot;name&quot;: &quot;&quot;,
  46. &quot;link&quot;: &quot;&quot;
  47. }
  48. }
  49. },
  50. &quot;profile 2&quot;: {
  51. &quot;name&quot;: &quot;Lonnie Gibson&quot;,
  52. &quot;Nick_name&quot;: &quot;Quentin&quot;,
  53. &quot;image_name&quot;: &quot;//placekitten.com/201&quot;,
  54. &quot;imageBG_name&quot;: &quot;LonnieGBG.jpg&quot;,
  55. &quot;contact_link&quot;: &quot;&quot;,
  56. &quot;description&quot;: &quot;&quot;,
  57. &quot;role&quot;: &quot;&quot;,
  58. &quot;social_links&quot;: {
  59. &quot;link_one&quot;: {
  60. &quot;name&quot;: &quot;&quot;,
  61. &quot;link&quot;: &quot;&quot;
  62. },
  63. &quot;link_two&quot;: {
  64. &quot;name&quot;: &quot;&quot;,
  65. &quot;link&quot;: &quot;&quot;
  66. },
  67. &quot;link_three&quot;: {
  68. &quot;name&quot;: &quot;&quot;,
  69. &quot;link&quot;: &quot;&quot;
  70. },
  71. &quot;link_four&quot;: {
  72. &quot;name&quot;: &quot;&quot;,
  73. &quot;link&quot;: &quot;&quot;
  74. },
  75. &quot;link_five&quot;: {
  76. &quot;name&quot;: &quot;&quot;,
  77. &quot;link&quot;: &quot;&quot;
  78. },
  79. &quot;link_six&quot;: {
  80. &quot;name&quot;: &quot;&quot;,
  81. &quot;link&quot;: &quot;&quot;
  82. },
  83. &quot;link_seven&quot;: {
  84. &quot;name&quot;: &quot;&quot;,
  85. &quot;link&quot;: &quot;&quot;
  86. }
  87. }
  88. }
  89. }
  90. }
  91. }

<!-- language: lang-css -->

  1. :root {
  2. font-family: sans-serif;
  3. }
  4. ul {
  5. list-style: none;
  6. margin: 0;
  7. padding: 0;
  8. }
  9. #profiles {
  10. display: flex;
  11. flex-wrap: wrap;
  12. gap: 1rem;
  13. }
  14. .card {
  15. border-radius: 8px;
  16. box-shadow: 4px 4px 8px #00000033;
  17. width: 200px;
  18. padding: .5rem;
  19. }
  20. .profile-img {
  21. width: 100px;
  22. aspect-ratio: 1;
  23. border-radius: 4px;
  24. }

<!-- language: lang-html -->

  1. &lt;div id=&quot;profiles&quot;&gt;&lt;/div&gt;

<!-- end snippet -->

Update:

I'd strongly recommend you use arrays for lists of items instead of naming each one, e.g. profile 1, profile 2.

Your list of profiles could look like this for example. (I've omitted some of the profile properties in the interest of brevity and readability.)

  1. {
  2. &quot;profiles&quot;: [
  3. {
  4. &quot;name&quot;: &quot;LoneOxi&quot;,
  5. &quot;nickname&quot;: &quot;&quot;,
  6. &quot;imageUrl&quot;: &quot;&quot;,
  7. },
  8. {
  9. &quot;name&quot;: &quot;Lonnie Gibson&quot;,
  10. &quot;nickname&quot;: &quot;Quentin&quot;,
  11. &quot;imageUrl&quot;: &quot;//placekitten.com/201&quot;
  12. }
  13. ]
  14. }

In addition to eliminating noise and complexity in the json, you can use the array iteration methods like map, forEach, for...of, etc. directly.

  1. obj.Profiles.forEach(profile =&gt; console.log(profile.name))

Same for link_one, link_two. There's no point in naming them this way. I'd recommend you either use the name as the key:

  1. {
  2. &quot;social_links&quot;: {
  3. &quot;facebook&quot;: &quot;https://...&quot;,
  4. &quot;twitter&quot;: &quot;https://...&quot;,
  5. &quot;instagram&quot;: &quot;https://....&quot;
  6. }
  7. }

You could iterate these using a for...in loop, or via Object.entries:

  1. for(const name in social_links) {
  2. const url = social_links[name];
  3. // do stuff with name and url
  4. }
  5. Object.entries(social_links).forEach(([name, url]) =&gt; {
  6. // do stuff with name and url
  7. });

Or just use an array of the objects you're already using:

  1. {
  2. &quot;social_links&quot;: [
  3. {
  4. &quot;name&quot;: &quot;facebook&quot;,
  5. &quot;link&quot;: &quot;https://...&quot;
  6. },
  7. {
  8. &quot;name&quot;: &quot;twitter&quot;,
  9. &quot;link&quot;: &quot;https://...&quot;
  10. },
  11. {
  12. &quot;name&quot;: &quot;instagram&quot;,
  13. &quot;link&quot;: &quot;https://...&quot;
  14. },
  15. ]
  16. }
  1. social_links.forEach(item =&gt; {
  2. // do stuff with item.name, item.link
  3. })

I think it's a good idea to keep the root of the json response as an object to allow for additional metadata or whatever, but taken together your API response might look something more like this.

  1. {
  2. metadata: {
  3. lastUpdated: &#39;2023-04-04&#39;
  4. },
  5. profiles: [
  6. {
  7. name: &quot;Lonnie Gibson&quot;,
  8. image: &quot;/path/to/avatar.jpg&quot;,
  9. bgImage: &quot;/path/to/bgImage.jpg&quot;,
  10. social: [
  11. {
  12. name: &#39;facebook&#39;,
  13. url: &#39;https://facebook.com/...&#39;
  14. },
  15. {
  16. name: &#39;twitter&#39;,
  17. url: &#39;https://twitter.com/...&#39;
  18. }
  19. ]
  20. },
  21. {
  22. name: &quot;Someone Else&quot;,
  23. image: &quot;/path/to/avatar.jpg&quot;,
  24. bgImage: &quot;/path/to/bgImage.jpg&quot;,
  25. social: [
  26. {
  27. name: &#39;facebook&#39;,
  28. url: &#39;https://facebook.com/...&#39;
  29. },
  30. {
  31. name: &#39;twitter&#39;,
  32. url: &#39;https://twitter.com/...&#39;
  33. }
  34. ]
  35. }
  36. ]
  37. }

huangapple
  • 本文由 发表于 2023年4月4日 14:01:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75925949.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定