How to rename JSON key
- Parse the JSON
const arr = JSON.parse(json);
- For each object in the JSON, rename the key:
obj.id = obj._id;
delete obj._id;
- Stringify the result
All together:
function renameKey ( obj, oldKey, newKey ) {
obj[newKey] = obj[oldKey];
delete obj[oldKey];
}
const json = `
[
{
"_id":"5078c3a803ff4197dc81fbfb",
"email":"user1@gmail.com",
"image":"some_image_url",
"name":"Name 1"
},
{
"_id":"5078c3a803ff4197dc81fbfc",
"email":"user2@gmail.com",
"image":"some_image_url",
"name":"Name 2"
}
]
`;
const arr = JSON.parse(json);
arr.forEach( obj => renameKey( obj, '_id', 'id' ) );
const updatedJson = JSON.stringify( arr );
console.log( updatedJson );
Python Edit/Rename Key Names in .json
There is no way to "change" a key name.
The best you can do is to copy the value to another key by using pop
:
d = {'old_name': 1}
d['new_name'] = d.pop('old_name')
print(d)
# {'new_name': 1}
Rename JSON key names
Trying to use duplicate keys in a JSON object is not recommended. You can see the problems that arise when you serialize and deserialize duplicate keys, or try to force them into a dictionary. The duplicate keys are not retained.
>>> from json import dumps, loads
>>> json = '{"a": "x", "a": "y"}'
>>> loads(json)
{'a': 'y'}
>>> json = {'a': 'x', 'a': 'y'}
>>> dumps(json)
'{"a": "y"}'
>>> json = {'a': 'x', 'a': 'y'}
>>> json
{'a': 'y'}
Instead you could try grouping all keys that start with "output"
into a list ["test", "test2", "something"]
.
from json import dumps
d = {
"Question Communicating": "Natural language",
"interpretation_type": "recognition",
"output1": "test",
"Question Learning": "Reinforcement",
"output2": "test2",
"output3": "something"
}
result = {}
for k, v in d.items():
if k.startswith("output"):
result.setdefault("output", []).append(v)
else:
result[k] = v
print(dumps(result, indent=4))
Output JSON:
{
"Question Communicating": "Natural language",
"interpretation_type": "recognition",
"output": [
"test",
"test2",
"something"
],
"Question Learning": "Reinforcement"
}
How to rename key for nested JSON object in Python
Do it after you load the JSON, so you can call the function on just the element you want.
obj = json.loads(jres);
for bucket in obj["aggregations"]["range"]["buckets"]:
for bucket2 in bucket["by ip"]["buckets"]:
rename_doc_count(bucket2)
And there's no need for a loop in rename_doc_count
, just fetch the specific dictionary element.
def rename_doc_count(obj):
if "doc_count" in obj:
obj["Number of unique events"] = obj["doc_count"]
del obj["doc_count"]
You mention that there can be sub-buckets that should also be renamed. You can do that by having rename_doc_count
call itself recursively. But you didn't show where those are in the structure, so I don't know precisely what it should look like. But it's similar to the loop after json.loads()
.
read and rename keys json file when a new file is added to a directory
You can turn the JSON from your JSON file into a dict with json.loads(your_entire_json_file_as_a_string)
Then you can directly key into your json to change the appropriate keys.
For Example:
import json
def get_json_file_as_string(filepath):
with open(filepath) as json_file:
return json_file.read().replace('\n', '')
file_path = changed_json_file_path
names_key = { 'a' : 'aa' , 'b' : 'bb', }
json_dict = json.loads(get_json_file_as_string(changed_json_file_path))
json_dict = {'aa':1, 'bb':2}
for new_key, old_key in names_key.items():
if old_key in json_dict:
json_dict[new_key] = json_dict[old_key]
json_dict.pop(old_key)
print(json_dict)
Edit
This depends on the structure of the data in your JSON file. But if it's just a simple list of name value pairs this will work nicely
How to rename key value pair within a nested json structure in C#
try this
var data= JObject.Parse(json);
var content = (JArray)data["cases"]["content"];
var jObj = new JObject();
foreach (var item in content)
{
var value = item["value"] is JObject ? (string)item["value"]["Value"] : (string)item["value"];
if (jObj.ContainsKey((string)item["field"])) jObj[(string)item["field"]] = value;
else jObj.Add((string)item["field"], value);
}
var newData= new JObject();
newData["status"] = data["status"];
newData["cases"] = new JObject();
newData["cases"]["id"] = data["cases"]["_id"];
newData["cases"]["nameLower"] = data["cases"]["nameLower"];
newData["cases"]["content"] = new JArray { jObj };
var newJson = newData.ToString();
new json
{
"status": "OK",
"cases": {
"id": "61f8126266221531009f8909",
"nameLower": "at&t - v.1 - 31.01.2022",
"content": [
{
"DATA": "11/23/2021 15:37:59",
"Other": "",
"SP": "14042547",
"AVAILABLE CLIENT": "Yes",
"REFERENCE CLIENT": "MR JOHN DOE",
"CABLE TYPE": "Rame",
"CABLES": "WALL",
"TERMINATION": "WALL",
"PLANT LOCATION": "PRIVATE PROPERTY",
"TRIAL PERIOD": "",
"EXECUTED BY:": "JOHN DOE"
}
]
}
}
Rename JSON key after a specific pattern
Here, one of solutions...
data = {
"quiz": {
"sport": {
"id": "77",
"q1": {
"question": "Which one is correct team name in NBA?",
"options": [
"New York Bulls",
"Huston Rocket"
],
"answer": "Huston Rocket"
}
},
"maths": {
"q1": {
"question": "5 + 7 = ?",
"options": [
"10",
"13"
],
"answer": "13"
},
}
}
}
for key in data.get('quiz'):
inner_data = data['quiz'][key]
if 'id' in inner_data and 'answer' in inner_data['q1']:
inner_data['q1']['answer_id'] = inner_data['q1'].pop('answer')
print(data)
Related Topics
Regex to Remove All Special Characters from String
Split a Comma-Separated String With Both Quoted and Unquoted Strings
Formatting Date in Linq-To-Entities Query Causes Exception
Smtpexception: Unable to Read Data from the Transport Connection: Net_Io_Connectionclosed
Check If a File Is Real or a Symbolic Link
How to Set Shadow Effect on Imageview
Post Json Array to MVC Controller
How to Make Blazor Http Get Json Async Request
How to Rename Keys Within a Json File
C# ASP.NET MVC Download a File Via Ajax
Rendering Views from External Assemblies in Mvc6
Visual Studio Solution Unavailable (Reload Doesn't Work)
How to Properly Make a Http Web Get Request
How to Convert HTML to Pdf Using Itextsharp