Are multi-line strings allowed in JSON?

前端 未结 9 1315
醉酒成梦
醉酒成梦 2020-11-22 04:21

Is it possible to have multi-line strings in JSON?

It\'s mostly for visual comfort so I suppose I can just turn word wrap on in my editor, but I\'m just kinda curious

相关标签:
9条回答
  • 2020-11-22 04:49

    I have had to do this for a small Node.js project and found this work-around:

    {
     "modify_head": [
    
      "<script type='text/javascript'>",
      "<!--",
      "  function drawSomeText(id) {",
      "  var pjs = Processing.getInstanceById(id);",
      "  var text = document.getElementById('inputtext').value;",
      "  pjs.drawText(text);}",
      "-->",
      "</script>"
    
     ],
    
     "modify_body": [
    
      "<input type='text' id='inputtext'></input>",
      "<button onclick=drawSomeText('ExampleCanvas')></button>"
    
     ],
    }
    

    This looks quite neat to me, appart from that I have to use double quotes everywhere. Though otherwise, I could, perhaps, use YAML, but that has other pitfalls and is not supported natively. Once parsed, I just use myData.modify_head.join('\n') or myData.modify_head.join(), depending upon whether I want a line break after each string or not.

    0 讨论(0)
  • 2020-11-22 04:50

    JSON doesn't allow breaking lines for readability.

    Your best bet is to use an IDE that will line-wrap for you.

    0 讨论(0)
  • 2020-11-22 04:56

    Unfortunately many of the answers here address the question of how to put a newline character in the string data. The question is how to make the code look nicer by splitting the string value across multiple lines of code. (And even the answers that recognize this provide "solutions" that assume one is free to change the data representation, which in many cases one is not.)

    And the worse news is, there is no good answer.

    In many programming languages, even if they don't explicitly support splitting strings across lines, you can still use string concatenation to get the desired effect; and as long as the compiler isn't awful this is fine.

    But json is not a programming language; it's just a data representation. You can't tell it to concatenate strings. Nor does its (fairly small) grammar include any facility for representing a string on multiple lines.

    Short of devising a pre-processor of some kind (and I, for one, don't feel like effectively making up my own language to solve this issue), there isn't a general solution to this problem. IF you can change the data format, then you can substitute an array of strings. Otherwise, this is one of the numerous ways that json isn't designed for human-readability.

    0 讨论(0)
提交回复
热议问题