Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert all the integer value to string in JSON

Tags:

java

json

My JSON string is:

{name:"MyNode", width:200, height:100}

I want to change it to:

{name:"MyNode", width:"200", height:"100"}

so that all integer values become strings


My main code is:

{
     "firstName": "John",
     "lastName": "Smith",
     "age": 25,
     "address":
     {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "xy": 10021
     },
     "IDNumber":
     [
         {
           "type": "home",
           "number": 1234
         },
         {
           "type": "fax",
           "number": 4567
         }
     ]
 }

I need all integer values become strings

like image 424
user940782 Avatar asked Sep 12 '11 14:09

user940782


People also ask

How can I convert JSON to string?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.

Can numbers be strings in JSON?

Valid Data Types In JSON, values must be one of the following data types: a string. a number. an object (JSON object)

Can I convert JSON to text?

Users can also Convert JSON File to Text by uploading the file. Download converted file with txt extension. JSON to Text Online works well on Windows, MAC, Linux, Chrome, Firefox, Edge, and Safari.

Can JSON return integer?

integer. The integer type is used for integral numbers. JSON does not have distinct types for integers and floating-point values.


2 Answers

That's a JavaScript object literal, not JSON. Anyway...

var obj = {name:"MyNode", width:200, height:100};

for (var k in obj)
{
    if (obj.hasOwnProperty(k))
    {
        obj[k] = String(obj[k]);
    }
}

// obj = {name:"MyNode", width: "200", height: "100"}

If you're actually working with JSON, not an object, JSON.parse() the string beforehand, and JSON.stringify() the object afterward.

like image 107
Matt Ball Avatar answered Sep 21 '22 19:09

Matt Ball


If you must operate on the JSON string :

json = json.replace (/:(\d+)([,\}])/g, ':"$1"$2');
like image 27
HBP Avatar answered Sep 23 '22 19:09

HBP