Convert all the integer value to string in JSON
Asked Answered
O

3

12

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

Oodles answered 12/9, 2011 at 14:39 Comment(3)
-1 for unanswerable question since you're not saying which programming language you are using.Kwang
@Matt Ball: I tagged the question with [javascript]. No language was specified but the post contained JS object literals (not JSON, as you pointed out in your answer). So I removed the [json] tag and replaced it with [javascript].Dilan
@Andy d'oh didn't look far back enough in the edit history, thank'yaGuzzle
G
10

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.

Guzzle answered 12/9, 2011 at 14:45 Comment(5)
actually i got the json value in my java code. so i have to do work in java only.Oodles
@user: that's the kind of thing you need to mention when you ask your question, rather than after you get answers.Dilan
@Matt Ball, just curious, why do you have the obj.hasOwnProperty check? Since you're iterating over the object's properties, normally you already know that the object has this property, or am I missing something?Kwang
@user are you using any JSON libraries? If not, check out Google Gson.Guzzle
@Laurent Object.hasOwnProperty() makes sure that you ignore unwanted properties from the object's prototype. See the note in yellow: developer.mozilla.org/en/JavaScript/Reference/Statements/…Guzzle
C
6

If you must operate on the JSON string :

json = json.replace (/:(\d+)([,\}])/g, ':"$1"$2');
Cralg answered 12/9, 2011 at 15:0 Comment(2)
i am using json-lib-2.4-jdk15.jar. There is no replace method in that jar. can we do the same thing in java. if can please suggest.Oodles
This was a very helpful answer. The reason to do this is if you have really large numbers (>53 bits of precision), then when you JSON.parse them, you lose precision. When you're using them as an ID, that's really bad. For my situation, since I never do math on them, I can treat them as strings and everything is great. Here's the function I used: json.replace (/:\s*(\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d\d+)\s*([,\}])/g, ':"$1"$2');. It has the advantage of only doing the replace on really big numbers, and it deals with spaces after the colon and before the comma or brace.Edina
I
0

I use

const stringifyNumbers = obj => {                                                                                      
  const result = {};                                                                                                   
  Object.entries(obj).map(entry => {                                                                                   
    const type = typeof entry[1];                                                                                      
    if (Array.isArray(entry[1])) {                                                                                     
      result[entry[0]] = entry[1].map(entry => stringifyNumbers(entry));                                               
    } else if (type === 'object' && !!entry[1]) {                                                                      
      result[entry[0]] = stringifyNumbers(entry[1]);                                                                   
    } else if (entry[1] === null) {                                                                                    
      result[entry[0]] = null;                                                                                         
    } else if (type === 'number') {                                                                                    
      result[entry[0]] = String(entry[1]);                                                                             
    } else {                                                                                                           
      result[entry[0]] = entry[1];                                                                                     
    }                                                                                                                  
  });                                                                                                                  
  return result;                                                                                                       
}   

most ids should be strings in my opinion. If your api cannot provide ids as strings this snippet will convert them.

Idealism answered 4/9, 2019 at 6:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.